Previous 15994 Revisions Next

r14135 Monday 23rd January, 2012 at 09:31:11 UTC by Miodrag Milanović
Sync with MAME r15118 (no whatsnew) note: pc_vga and floppy ui support not overwritten
[ROOT]makefile
[src/emu]video.c
[src/emu/drivers]xtal.h
[src/emu/sound]samples.c
[src/emu/video]polynew.h
[src/lib]lib.mak
[src/lib/libflac]libflac++* libflac++.mak* libflac.mak*
[src/lib/libflac/include]flac++*
[src/lib/libflac/include/flac]all.h* assert.h* callback.h* export.h* format.h* metadata.h* ordinals.h* stream_decoder.h* stream_encoder.h*
[src/lib/libflac/include/flac++]all.h* decoder.h* encoder.h* export.h* metadata.h*
[src/lib/libflac/include/private]all.h* bitmath.h* bitreader.h* bitwriter.h* cpu.h* crc.h* fixed.h* float.h* format.h* lpc.h* md5.h* memory.h* metadata.h* stream_encoder_framing.h* window.h*
[src/lib/libflac/include/protected]all.h* stream_decoder.h* stream_encoder.h*
[src/lib/libflac/include/share]alloc.h* utf8.h*
[src/lib/libflac/libflac]bitmath.c* bitreader.c* bitwriter.c* cpu.c* crc.c* fixed.c* float.c* format.c* lpc.c* md5.c* memory.c* metadata_iterators.c* metadata_object.c* stream_decoder.c* stream_encoder.c* stream_encoder_framing.c* window.c*
[src/lib/libflac/libflac++]metadata.cpp* stream_decoder.cpp* stream_encoder.cpp*
[src/lib/util]cdrom.h chd.c chd.h
[src/mame]mame.lst mame.mak
[src/mame/drivers]asuka.c bbusters.c champbwl.c crystal.c dec8.c dreamwld.c dynduke.c galpanic.c gberet.c gts80a.c hvyunit.c popobear.c* raiden.c s11c.c sandscrp.c seta.c slapfght.c snowbros.c taito.c twin16.c wwfwfest.c
[src/mame/includes]gberet.h
[src/mame/video]airbustr.c armedf.c baraduke.c bionicc.c blktiger.c bosco.c commando.c cps1.c crshrace.c deco_mlc.c djboy.c dooyong.c exedexes.c galaga.c gaplus.c gng.c konamigx.c ladybug.c lastduel.c macrossp.c model1.c mw8080bw.c namcos86.c othldrby.c pgm.c psikyo.c psikyosh.c redclash.c seta.c sidearms.c snk6502.c srumbler.c taotaido.c tceptor.c tigeroad.c tmnt.c tnzs.c toaplan1.c toki.c twincobr.c tx1.c
[src/osd/sdl]sdlsocket.c
[src/tools]chdman.c tools.mak

src/mame/mame.lst
r14134r14135
32363236// Capcom ZN1
32373237cpzn1
32383238ts2         // Battle Arena Toshinden 2 (USA 951124)
3239ts2a         // Battle Arena Toshinden 2 (USA 951124) - Alternate
3239ts2a         // Battle Arena Toshinden 2 (USA 951124)
32403240ts2j         // Battle Arena Toshinden 2 (JAPAN 951124)
32413241starglad      // Star Gladiator (USA 960627)
32423242stargladj      // Star Gladiator (JAPAN 960627)
r14134r14135
1016410164cardline      // (c) 199? Veltmeijer
1016510165bmcbowl         // (c) 1994 BMC
1016610166koftball      // (c) 1995 BMC
10167popobear      // (c) 2000 BMC
1016710168mpoker         // (c) 1983 Merit
1016810169pitboss         // (c) 1983 Merit
1016910170pitbossa      // (c) 1983 Merit
r14134r14135
1085210853lucky8a         // (c) 1989 Wing Co. Ltd
1085310854lucky8b         // (c) 1989 Wing Co. Ltd
1085410855luckgrln      // (c) 1991 Wing Co. Ltd
108567smash         // (c) 1993 Sovic
1085510857luckylad      // (c) 1985 Wing Co. Ltd
1085610858bingowng      // (c) 1993 Wing Co. Ltd
1085710859bingownga      // (c) 1993 Wing Co. Ltd
r14134r14135
2057620578tmspoker
2057720579tonton
2057820580kas89
20579
205807smash
src/mame/includes/gberet.h
r14134r14135
1919   size_t      m_spriteram_size;
2020
2121   /* video-related */
22   tilemap_t     *m_bg_tilemap;
22   tilemap_t * m_bg_tilemap;
2323   UINT8       m_spritebank;
2424
2525   /* misc */
26   UINT8       m_nmi_enable;
27   UINT8       m_irq_enable;
26   UINT8 *     m_soundlatch;
27   UINT8       m_interrupt_mask;
28   UINT8       m_interrupt_ticks;
2829};
2930
3031
src/mame/mame.mak
r14134r14135
524524$(MAMEOBJ)/bmc.a: \
525525   $(DRIVERS)/bmcbowl.o \
526526   $(DRIVERS)/koftball.o \
527   $(DRIVERS)/popobear.o \
527528
528529$(MAMEOBJ)/capcom.a: \
529530   $(DRIVERS)/1942.o $(VIDEO)/1942.o \
src/mame/video/blktiger.c
r14134r14135
253253
254254SCREEN_VBLANK( blktiger )
255255{
256   // rising edge
257   if (vblank_on)
256   // falling edge
257   if (!vblank_on)
258258   {
259259      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
260260
src/mame/video/deco_mlc.c
r14134r14135
496496
497497SCREEN_VBLANK( mlc )
498498{
499   // rising edge
500   if (vblank_on)
499   // falling edge
500   if (!vblank_on)
501501   {
502502      deco_mlc_state *state = screen.machine().driver_data<deco_mlc_state>();
503503      /* Spriteram is definitely double buffered, as the vram lookup tables
src/mame/video/twincobr.c
r14134r14135
518518
519519SCREEN_VBLANK( toaplan0 )
520520{
521   // rising edge
522   if (vblank_on)
521   // falling edge
522   if (!vblank_on)
523523   {
524524      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
525525
src/mame/video/gaplus.c
r14134r14135
331331
332332SCREEN_VBLANK( gaplus )   /* update starfields */
333333{
334   // rising edge
335   if (vblank_on)
334   // falling edge
335   if (!vblank_on)
336336   {
337337      gaplus_state *state = screen.machine().driver_data<gaplus_state>();
338338      struct star *stars = state->m_stars;
src/mame/video/exedexes.c
r14134r14135
247247
248248SCREEN_VBLANK( exedexes )
249249{
250   // rising edge
251   if (vblank_on)
250   // falling edge
251   if (!vblank_on)
252252   {
253253      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
254254
src/mame/video/armedf.c
r14134r14135
433433
434434SCREEN_VBLANK( armedf )
435435{
436   // rising edge
437   if (vblank_on)
436   // falling edge
437   if (!vblank_on)
438438   {
439439      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
440440
src/mame/video/model1.c
r14134r14135
15391539
15401540SCREEN_VBLANK(model1)
15411541{
1542   // on falling edge
1543   if (!vblank_on)
1542   // on rising edge
1543   if (vblank_on)
15441544   {
15451545      tgp_scan(screen.machine());
15461546      end_frame(screen.machine());
src/mame/video/mw8080bw.c
r14134r14135
313313
314314SCREEN_VBLANK( phantom2 )
315315{
316   // rising edge
317   if (vblank_on)
316   // falling edge
317   if (!vblank_on)
318318   {
319319      mw8080bw_state *state = screen.machine().driver_data<mw8080bw_state>();
320320
src/mame/video/namcos86.c
r14134r14135
398398
399399SCREEN_VBLANK( namcos86 )
400400{
401   // rising edge
402   if (vblank_on)
401   // falling edge
402   if (!vblank_on)
403403   {
404404      namcos86_state *state = screen.machine().driver_data<namcos86_state>();
405405      if (state->m_copy_sprites)
src/mame/video/cps1.c
r14134r14135
29502950
29512951SCREEN_VBLANK( cps1 )
29522952{
2953   // rising edge
2954   if (vblank_on)
2953   // falling edge
2954   if (!vblank_on)
29552955   {
29562956      cps_state *state = screen.machine().driver_data<cps_state>();
29572957
src/mame/video/othldrby.c
r14134r14135
226226
227227SCREEN_VBLANK( othldrby )
228228{
229   // rising edge
230   if (vblank_on)
229   // falling edge
230   if (!vblank_on)
231231   {
232232      othldrby_state *state = screen.machine().driver_data<othldrby_state>();
233233
src/mame/video/toaplan1.c
r14134r14135
12191219
12201220SCREEN_VBLANK( rallybik )
12211221{
1222   // rising edge
1223   if (vblank_on)
1222   // falling edge
1223   if (!vblank_on)
12241224   {
12251225      toaplan1_state *state = screen.machine().driver_data<toaplan1_state>();
12261226
r14134r14135
12301230
12311231SCREEN_VBLANK( toaplan1 )
12321232{
1233   // rising edge
1234   if (vblank_on)
1233   // falling edge
1234   if (!vblank_on)
12351235   {
12361236      toaplan1_state *state = screen.machine().driver_data<toaplan1_state>();
12371237
r14134r14135
12421242
12431243SCREEN_VBLANK( samesame )
12441244{
1245   // rising edge
1246   if (vblank_on)
1245   // falling edge
1246   if (!vblank_on)
12471247   {
12481248      toaplan1_state *state = screen.machine().driver_data<toaplan1_state>();
12491249
src/mame/video/tmnt.c
r14134r14135
833833
834834SCREEN_VBLANK( blswhstl )
835835{
836   // on falling edge
837   if (!vblank_on)
836   // on rising edge
837   if (vblank_on)
838838   {
839839      tmnt_state *state = screen.machine().driver_data<tmnt_state>();
840840      k053245_clear_buffer(state->m_k053245);
src/mame/video/bionicc.c
r14134r14135
262262
263263SCREEN_VBLANK( bionicc )
264264{
265   // rising edge
266   if (vblank_on)
265   // falling edge
266   if (!vblank_on)
267267   {
268268      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
269269
src/mame/video/psikyo.c
r14134r14135
867867
868868SCREEN_VBLANK( psikyo )
869869{
870   // rising edge
871   if (vblank_on)
870   // falling edge
871   if (!vblank_on)
872872   {
873873      psikyo_state *state = screen.machine().driver_data<psikyo_state>();
874874      memcpy(state->m_spritebuf2, state->m_spritebuf1, 0x2000);
src/mame/video/pgm.c
r14134r14135
675675
676676SCREEN_VBLANK( pgm )
677677{
678   // rising edge
679   if (vblank_on)
678   // falling edge
679   if (!vblank_on)
680680   {
681681      pgm_state *state = screen.machine().driver_data<pgm_state>();
682682
src/mame/video/bosco.c
r14134r14135
319319
320320SCREEN_VBLANK( bosco )
321321{
322   // rising edge
323   if (vblank_on)
322   // falling edge
323   if (!vblank_on)
324324   {
325325      bosco_state *state =  screen.machine().driver_data<bosco_state>();
326326      static const int speedsx[8] = { -1, -2, -3, 0, 3, 2, 1, 0 };
src/mame/video/lastduel.c
r14134r14135
308308
309309SCREEN_VBLANK( lastduel )
310310{
311   // rising edge
312   if (vblank_on)
311   // falling edge
312   if (!vblank_on)
313313   {
314314      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
315315
src/mame/video/redclash.c
r14134r14135
419419
420420SCREEN_VBLANK( redclash )
421421{
422   // rising edge
423   if (vblank_on)
422   // falling edge
423   if (!vblank_on)
424424      redclash_update_stars_state(screen.machine());
425425}
426426
src/mame/video/tceptor.c
r14134r14135
569569
570570SCREEN_VBLANK( tceptor )
571571{
572   // rising edge
573   if (vblank_on)
572   // falling edge
573   if (!vblank_on)
574574   {
575575      tceptor_state *state = screen.machine().driver_data<tceptor_state>();
576576      memcpy(state->m_sprite_ram_buffered, state->m_sprite_ram, 0x200);
src/mame/video/commando.c
r14134r14135
147147
148148SCREEN_VBLANK( commando )
149149{
150   // rising edge
151   if (vblank_on)
150   // falling edge
151   if (!vblank_on)
152152   {
153153      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
154154
src/mame/video/gng.c
r14134r14135
152152
153153SCREEN_VBLANK( gng )
154154{
155   // rising edge
156   if (vblank_on)
155   // falling edge
156   if (!vblank_on)
157157   {
158158      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
159159
src/mame/video/seta.c
r14134r14135
10671067
10681068SCREEN_VBLANK( setaroul )
10691069{
1070   // rising edge
1071   if (vblank_on)
1070   // falling edge
1071   if (!vblank_on)
10721072      screen.machine().device<seta001_device>("spritegen")->tnzs_eof();
10731073}
10741074
src/mame/video/tnzs.c
r14134r14135
5555
5656SCREEN_VBLANK( tnzs )
5757{
58   // rising edge
59   if (vblank_on)
58   // falling edge
59   if (!vblank_on)
6060      screen.machine().device<seta001_device>("spritegen")->tnzs_eof();
6161}
src/mame/video/toki.c
r14134r14135
3535
3636SCREEN_VBLANK( toki )
3737{
38   // rising edge
39   if (vblank_on)
38   // falling edge
39   if (!vblank_on)
4040      buffer_spriteram16_w(screen.machine().device("maincpu")->memory().space(AS_PROGRAM), 0, 0, 0xffff);
4141}
4242
4343SCREEN_VBLANK( tokib )
4444{
45   // rising edge
46   if (vblank_on)
45   // falling edge
46   if (!vblank_on)
4747      buffer_spriteram16_w(screen.machine().device("maincpu")->memory().space(AS_PROGRAM), 0, 0, 0xffff);
4848}
4949
src/mame/video/galaga.c
r14134r14135
580580
581581SCREEN_VBLANK( galaga )
582582{
583   // rising edge
584   if (vblank_on)
583   // falling edge
584   if (!vblank_on)
585585   {
586586      galaga_state *state =  screen.machine().driver_data<galaga_state>();
587587      /* this function is called by galaga_interrupt_1() */
src/mame/video/sidearms.c
r14134r14135
368368
369369SCREEN_VBLANK( sidearms )
370370{
371   // rising edge
372   if (vblank_on)
371   // falling edge
372   if (!vblank_on)
373373   {
374374      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
375375
src/mame/video/djboy.c
r14134r14135
8383
8484SCREEN_VBLANK( djboy )
8585{
86   // rising edge
87   if (vblank_on)
86   // falling edge
87   if (!vblank_on)
8888   {
8989      djboy_state *state = screen.machine().driver_data<djboy_state>();
9090      pandora_eof(state->m_pandora);
src/mame/video/snk6502.c
r14134r14135
198198
199199   VIDEO_START_CALL( snk6502 );
200200
201   state->m_bg_tilemap->set_scrolldy(-16, 0);
202   state->m_fg_tilemap->set_scrolldy(-16, 0);
201   state->m_bg_tilemap->set_scrolldy(-16, -16);
202   state->m_fg_tilemap->set_scrolldy(-16, -16);
203203}
204204
205205
src/mame/video/tx1.c
r14134r14135
11261126
11271127SCREEN_VBLANK( tx1 )
11281128{
1129   tx1_state *state = screen.machine().driver_data<tx1_state>();
1130   /* /VSYNC: Update TZ113 */
1131   state->m_vregs.slin_val += state->m_vregs.slin_inc;
1129   // falling edge
1130   if (!vblank_on)
1131   {
1132      tx1_state *state = screen.machine().driver_data<tx1_state>();
1133
1134      /* /VSYNC: Update TZ113 */
1135      state->m_vregs.slin_val += state->m_vregs.slin_inc;
1136   }
11321137}
11331138
11341139static void tx1_combine_layers(running_machine &machine, bitmap_ind16 &bitmap, int screen)
r14134r14135
30293034
30303035SCREEN_VBLANK( buggyboy )
30313036{
3032   // rising edge
3033   if (vblank_on)
3037   // falling edge
3038   if (!vblank_on)
30343039   {
30353040      tx1_state *state = screen.machine().driver_data<tx1_state>();
30363041
src/mame/video/srumbler.c
r14134r14135
172172
173173SCREEN_VBLANK( srumbler )
174174{
175   // rising edge
176   if (vblank_on)
175   // falling edge
176   if (!vblank_on)
177177   {
178178      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
179179
src/mame/video/tigeroad.c
r14134r14135
173173
174174SCREEN_VBLANK( tigeroad )
175175{
176   // rising edge
177   if (vblank_on)
176   // falling edge
177   if (!vblank_on)
178178   {
179179      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
180180
src/mame/video/psikyosh.c
r14134r14135
13101310
13111311SCREEN_VBLANK( psikyosh )
13121312{
1313   // rising edge
1314   if (vblank_on)
1313   // falling edge
1314   if (!vblank_on)
13151315   {
13161316      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
13171317      buffer_spriteram32_w(space, 0, 0, 0xffffffff);
src/mame/video/konamigx.c
r14134r14135
502502
503503   // adjust insertion points and pre-entry constants
504504   eax = (dst_y - dst_miny) * GX_ZBUFW + (dst_x - dst_minx) + dst_w;
505//  db0 = z8 = (UINT8)zcode;
506//  db1 = p8 = (UINT8)pri;
505   z8 = (UINT8)zcode;
506   p8 = (UINT8)pri;
507507   ozbuf_ptr += eax;
508508   szbuf_ptr += eax << 1;
509509   dst_ptr += dst_y * dst_pitch + dst_x + dst_w;
src/mame/video/ladybug.c
r14134r14135
308308
309309SCREEN_VBLANK( sraider )   /* update starfield position */
310310{
311   // rising edge
312   if (vblank_on)
311   // falling edge
312   if (!vblank_on)
313313      redclash_update_stars_state(screen.machine());
314314}
315315
src/mame/video/macrossp.c
r14134r14135
431431
432432SCREEN_VBLANK( macrossp )
433433{
434   // rising edge
435   if (vblank_on)
434   // falling edge
435   if (!vblank_on)
436436   {
437437      macrossp_state *state = screen.machine().driver_data<macrossp_state>();
438438
src/mame/video/taotaido.c
r14134r14135
226226
227227SCREEN_VBLANK( taotaido )
228228{
229   // rising edge
230   if (vblank_on)
229   // falling edge
230   if (!vblank_on)
231231   {
232232      taotaido_state *state = screen.machine().driver_data<taotaido_state>();
233233      /* sprites need to be delayed by 2 frames? */
src/mame/video/baraduke.c
r14134r14135
342342
343343SCREEN_VBLANK( baraduke )
344344{
345   // rising edge
346   if (vblank_on)
345   // falling edge
346   if (!vblank_on)
347347   {
348348      baraduke_state *state = screen.machine().driver_data<baraduke_state>();
349349      if (state->m_copy_sprites)
src/mame/video/crshrace.c
r14134r14135
219219
220220SCREEN_VBLANK( crshrace )
221221{
222   // rising edge
223   if (vblank_on)
222   // falling edge
223   if (!vblank_on)
224224   {
225225      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
226226
src/mame/video/airbustr.c
r14134r14135
148148
149149SCREEN_VBLANK( airbustr )
150150{
151   // rising edge
152   if (vblank_on)
151   // falling edge
152   if (!vblank_on)
153153   {
154154      airbustr_state *state = screen.machine().driver_data<airbustr_state>();
155155
src/mame/video/dooyong.c
r14134r14135
933933
934934SCREEN_VBLANK( dooyong )
935935{
936   // rising edge
937   if (vblank_on)
936   // falling edge
937   if (!vblank_on)
938938   {
939939      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
940940
r14134r14135
944944
945945SCREEN_VBLANK( rshark )
946946{
947   // rising edge
948   if (vblank_on)
947   // falling edge
948   if (!vblank_on)
949949   {
950950      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
951951
src/mame/drivers/dynduke.c
r14134r14135
287287   MCFG_MACHINE_RESET(seibu_sound)
288288
289289   // video hardware
290   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM)
290   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
291291
292292   MCFG_SCREEN_ADD("screen", RASTER)
293293   MCFG_SCREEN_REFRESH_RATE(60)
src/mame/drivers/snowbros.c
r14134r14135
9494
9595static SCREEN_VBLANK( snowbros )
9696{
97   // rising edge
98   if (vblank_on)
97   // falling edge
98   if (!vblank_on)
9999   {
100100      device_t *pandora = screen.machine().device("pandora");
101101      pandora_eof(pandora);
src/mame/drivers/seta.c
r14134r14135
15471547*/
15481548static SCREEN_VBLANK( seta_buffer_sprites )
15491549{
1550   // rising edge
1551   if (vblank_on)
1550   // falling edge
1551   if (!vblank_on)
15521552   {
15531553      //seta_state *state = machine.driver_data<seta_state>();
15541554      screen.machine().device<seta001_device>("spritegen")->setac_eof();
src/mame/drivers/champbwl.c
r14134r14135
462462
463463SCREEN_VBLANK( champbwl )
464464{
465   // rising edge
466   if (vblank_on)
465   // falling edge
466   if (!vblank_on)
467467      screen.machine().device<seta001_device>("spritegen")->tnzs_eof();
468468}
469469
r14134r14135
521521
522522static SCREEN_VBLANK( doraemon )
523523{
524   // rising edge
525   if (vblank_on)
524   // falling edge
525   if (!vblank_on)
526526      screen.machine().device<seta001_device>("spritegen")->setac_eof();
527527}
528528
src/mame/drivers/raiden.c
r14134r14135
244244
245245static SCREEN_VBLANK( raiden )
246246{
247   // rising edge
248   if (vblank_on)
247   // falling edge
248   if (!vblank_on)
249249   {
250250      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
251251      buffer_spriteram16_w(space,0,0,0xffff); /* Could be a memory location instead */
src/mame/drivers/s11c.c
r14134r14135
356356GAME(1990,   pool_l6,   pool_l7,   williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Bally",            "Pool Sharks (LA-6)",                     GAME_IS_SKELETON_MECHANICAL)
357357GAME(1990,   pool_le2,   pool_l7,   williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Bally",            "Pool Sharks (LE-2)",                     GAME_IS_SKELETON_MECHANICAL)
358358GAME(1989,   pool_p7,   pool_l7,   williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Bally",            "Pool Sharks (PA-7)",                     GAME_IS_SKELETON_MECHANICAL)
359GAME(1990,   radcl_l1,   0,         williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Bally",            "Radical (L-1)",                        GAME_IS_SKELETON_MECHANICAL)
360GAME(1990,   radcl_g1,   radcl_l1,   williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Bally",            "Radical (G-1)",                        GAME_IS_SKELETON_MECHANICAL)
361GAME(1990,   radcl_p3,   radcl_l1,   williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Bally",            "Radical (P-3)",                        GAME_IS_SKELETON_MECHANICAL)
359GAME(1990,   radcl_l1,   0,         williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Bally",            "Radical! (L-1)",                        GAME_IS_SKELETON_MECHANICAL)
360GAME(1990,   radcl_g1,   radcl_l1,   williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Bally",            "Radical! (G-1)",                        GAME_IS_SKELETON_MECHANICAL)
361GAME(1990,   radcl_p3,   radcl_l1,   williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Bally",            "Radical! (P-3)",                        GAME_IS_SKELETON_MECHANICAL)
362362GAME(1990,   rvrbt_l3,   0,         williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Williams",            "Riverboat Gambler (L-3)",                  GAME_IS_SKELETON_MECHANICAL)
363363GAME(1990,   rollr_l2,   0,         williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Williams",            "Rollergames (L-2)",                     GAME_IS_SKELETON_MECHANICAL)
364364GAME(1991,   rollr_ex,   rollr_l2,   williams_s11c,   williams_s11c,   williams_s11c,   ROT0,   "Williams",            "Rollergames (EXPERIMENTAL)",               GAME_IS_SKELETON_MECHANICAL)
src/mame/drivers/slapfght.c
r14134r14135
770770   MCFG_MACHINE_RESET(slapfight)
771771
772772   /* video hardware */
773   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM)
773   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
774774
775775   MCFG_SCREEN_ADD("screen", RASTER)
776776   MCFG_SCREEN_REFRESH_RATE(60)
r14134r14135
816816   MCFG_MACHINE_RESET(slapfight)
817817
818818   /* video hardware */
819   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM)
819   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
820820
821821   MCFG_SCREEN_ADD("screen", RASTER)
822822   MCFG_SCREEN_REFRESH_RATE(60)
r14134r14135
864864   MCFG_MACHINE_RESET(slapfight)
865865
866866   /* video hardware */
867   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM)
867   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
868868
869869   MCFG_SCREEN_ADD("screen", RASTER)
870870   MCFG_SCREEN_REFRESH_RATE(60)
r14134r14135
913913   MCFG_MACHINE_RESET(slapfight)
914914
915915   /* video hardware */
916   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM)
916   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
917917
918918   MCFG_SCREEN_ADD("screen", RASTER)
919919   MCFG_SCREEN_REFRESH_RATE(60)
src/mame/drivers/wwfwfest.c
r14134r14135
383383
384384static SCREEN_VBLANK( wwfwfest )
385385{
386   // rising edge
387   if (vblank_on)
386   // falling edge
387   if (!vblank_on)
388388   {
389389      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
390390
src/mame/drivers/taito.c
r14134r14135
604604   ROM_RELOAD( 0xf000, 0x1000)
605605ROM_END
606606
607GAME(198?,   taitest,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Taito Test Fixture",            GAME_IS_SKELETON_MECHANICAL)
608GAME(1981,   cavnegro,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Cavaleiro Negro",            GAME_IS_SKELETON_MECHANICAL)
609GAME(1981,   cavnegro1,   cavnegro,   taito,   taito,   taito,   ROT0,   "Taito",   "Cavaleiro Negro (alternate set 1)",            GAME_IS_SKELETON_MECHANICAL)
610GAME(1981,   cavnegro2,   cavnegro,   taito,   taito,   taito,   ROT0,   "Taito",   "Cavaleiro Negro (alternate set 2)",            GAME_IS_SKELETON_MECHANICAL)
611GAME(1981,   cosmic,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Cosmic",            GAME_IS_SKELETON_MECHANICAL)
612GAME(1980,   drakor,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Drakor",            GAME_IS_SKELETON_MECHANICAL)
613GAME(1981,   fireact,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Fire Action",            GAME_IS_SKELETON_MECHANICAL)
614GAME(198?,   fireactd,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Fire Action Deluxe",            GAME_IS_SKELETON_MECHANICAL)
615GAME(1982,   gemini2k,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Gemini 2000",            GAME_IS_SKELETON_MECHANICAL)
616GAME(1982,   gemini2k1,   gemini2k,   taito,   taito,   taito,   ROT0,   "Taito",   "Gemini 2000 (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
617GAME(1982,   gork,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Gork",            GAME_IS_SKELETON_MECHANICAL)
618GAME(1982,   hawkman,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Hawkman",            GAME_IS_SKELETON_MECHANICAL)
619GAME(1982,   hawkman1,   hawkman,   taito,   taito,   taito,   ROT0,   "Taito",   "Hawkman (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
620GAME(1981,   ladylukt,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Lady Luck (Taito)",            GAME_IS_SKELETON_MECHANICAL)
621GAME(1982,   lunelle,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Lunelle",            GAME_IS_SKELETON_MECHANICAL)
622GAME(1980,   meteort,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Meteor (Taito)",            GAME_IS_SKELETON_MECHANICAL)
623GAME(1984,   mrblack,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Mr. Black",            GAME_IS_SKELETON_MECHANICAL)
624GAME(1985,   mrblack1,   mrblack,   taito,   taito,   taito,   ROT0,   "Taito",   "Mr. Black (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
625GAME(1980,   obaoba,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Oba-Oba",            GAME_IS_SKELETON_MECHANICAL)
626GAME(1980,   obaoba1,   obaoba,      taito,   taito,   taito,   ROT0,   "Taito",   "Oba-Oba (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
627GAME(198?,   polar,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Polar Explorer",            GAME_IS_SKELETON_MECHANICAL)
628GAME(1982,   rally,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Rally",            GAME_IS_SKELETON_MECHANICAL)
629GAME(1982,   sharkt,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Shark (Taito)",            GAME_IS_SKELETON_MECHANICAL)
630GAME(1979,   shock,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Shock",            GAME_IS_SKELETON_MECHANICAL)
631GAME(1982,   snake,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Snake Machine",            GAME_IS_SKELETON_MECHANICAL)
632GAME(1985,   sshuttle,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Space Shuttle (Taito)",            GAME_IS_SKELETON_MECHANICAL)
633GAME(1985,   sshuttle1,   sshuttle,   taito,   taito,   taito,   ROT0,   "Taito",   "Space Shuttle (Taito) (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
634GAME(1982,   stest,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Speed Test",            GAME_IS_SKELETON_MECHANICAL)
635GAME(1981,   sureshop,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Sure Shot (Pinball)",            GAME_IS_SKELETON_MECHANICAL)
636GAME(1982,   titan,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Titan",            GAME_IS_SKELETON_MECHANICAL)
637GAME(1982,   titan1,      titan,      taito,   taito,   taito,   ROT0,   "Taito",   "Titan (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
638GAME(198?,   vegast,      ladylukt,   taito,   taito,   taito,   ROT0,   "Taito",   "Vegas (Taito)",            GAME_IS_SKELETON_MECHANICAL)
639GAME(198?,   voleybal,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Voley Ball",            GAME_IS_SKELETON_MECHANICAL)
640GAME(1982,   vortexp,   0,         taito,   taito,   taito,   ROT0,   "Taito",   "Vortex (Pinball)",            GAME_IS_SKELETON_MECHANICAL)
641GAME(1982,   zarza,      0,         taito,   taito,   taito,   ROT0,   "Taito",   "Zarza",            GAME_IS_SKELETON_MECHANICAL)
642GAME(1982,   zarza1,      zarza,      taito,   taito,   taito,   ROT0,   "Taito",   "Zarza (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
643GAME(198?,   mrblkz80,   mrblack,   taito,   taito,   taito,   ROT0,   "Taito",   "Mr. Black (Z-80 CPU)",            GAME_IS_SKELETON_MECHANICAL)
607GAME(198?,   taitest,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Taito Test Fixture",            GAME_IS_SKELETON_MECHANICAL)
608GAME(1981,   cavnegro,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Cavaleiro Negro",            GAME_IS_SKELETON_MECHANICAL)
609GAME(1981,   cavnegro1,   cavnegro,   taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Cavaleiro Negro (alternate set 1)",            GAME_IS_SKELETON_MECHANICAL)
610GAME(1981,   cavnegro2,   cavnegro,   taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Cavaleiro Negro (alternate set 2)",            GAME_IS_SKELETON_MECHANICAL)
611GAME(1981,   cosmic,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Cosmic",            GAME_IS_SKELETON_MECHANICAL)
612GAME(1980,   drakor,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Drakor",            GAME_IS_SKELETON_MECHANICAL)
613GAME(1981,   fireact,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Fire Action",            GAME_IS_SKELETON_MECHANICAL)
614GAME(198?,   fireactd,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Fire Action Deluxe",            GAME_IS_SKELETON_MECHANICAL)
615GAME(1982,   gemini2k,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Gemini 2000",            GAME_IS_SKELETON_MECHANICAL)
616GAME(1982,   gemini2k1,   gemini2k,   taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Gemini 2000 (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
617GAME(1982,   gork,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Gork",            GAME_IS_SKELETON_MECHANICAL)
618GAME(1982,   hawkman,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Hawkman",            GAME_IS_SKELETON_MECHANICAL)
619GAME(1982,   hawkman1,   hawkman,   taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Hawkman (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
620GAME(1981,   ladylukt,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Lady Luck (Taito)",            GAME_IS_SKELETON_MECHANICAL)
621GAME(1982,   lunelle,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Lunelle",            GAME_IS_SKELETON_MECHANICAL)
622GAME(1980,   meteort,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Meteor (Taito)",            GAME_IS_SKELETON_MECHANICAL)
623GAME(1984,   mrblack,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Mr. Black",            GAME_IS_SKELETON_MECHANICAL)
624GAME(1985,   mrblack1,   mrblack,   taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Mr. Black (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
625GAME(1980,   obaoba,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Oba-Oba",            GAME_IS_SKELETON_MECHANICAL)
626GAME(1980,   obaoba1,   obaoba,      taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Oba-Oba (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
627GAME(198?,   polar,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Polar Explorer",            GAME_IS_SKELETON_MECHANICAL)
628GAME(1980,   rally,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Rally",            GAME_IS_SKELETON_MECHANICAL)
629GAME(1982,   sharkt,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Shark (Taito)",            GAME_IS_SKELETON_MECHANICAL)
630GAME(1979,   shock,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Shock",            GAME_IS_SKELETON_MECHANICAL)
631GAME(1982,   snake,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Snake Machine",            GAME_IS_SKELETON_MECHANICAL)
632GAME(1985,   sshuttle,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Space Shuttle (Taito)",            GAME_IS_SKELETON_MECHANICAL)
633GAME(1985,   sshuttle1,   sshuttle,   taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Space Shuttle (Taito) (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
634GAME(1982,   stest,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Speed Test",            GAME_IS_SKELETON_MECHANICAL)
635GAME(1981,   sureshop,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Sure Shot (Pinball)",            GAME_IS_SKELETON_MECHANICAL)
636GAME(1982,   titan,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Titan",            GAME_IS_SKELETON_MECHANICAL)
637GAME(1982,   titan1,      titan,      taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Titan (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
638GAME(198?,   vegast,      ladylukt,   taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Vegas (Taito)",            GAME_IS_SKELETON_MECHANICAL)
639GAME(198?,   voleybal,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Voley Ball",            GAME_IS_SKELETON_MECHANICAL)
640GAME(1982,   vortexp,   0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Vortex (Pinball)",            GAME_IS_SKELETON_MECHANICAL)
641GAME(1982,   zarza,      0,         taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Zarza",            GAME_IS_SKELETON_MECHANICAL)
642GAME(1982,   zarza1,      zarza,      taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Zarza (alternate set)",            GAME_IS_SKELETON_MECHANICAL)
643GAME(198?,   mrblkz80,   mrblack,   taito,   taito,   taito,   ROT0,   "Taito do Brasil",   "Mr. Black (Z-80 CPU)",            GAME_IS_SKELETON_MECHANICAL)
src/mame/drivers/crystal.c
r14134r14135
696696
697697static SCREEN_VBLANK(crystal)
698698{
699   // rising edge
700   if (vblank_on)
699   // falling edge
700   if (!vblank_on)
701701   {
702702      crystal_state *state = screen.machine().driver_data<crystal_state>();
703703      address_space *space = screen.machine().device("maincpu")->memory().space(AS_PROGRAM);
src/mame/drivers/popobear.c
r0r14135
1/* Popo Bear - BMC-A00211
2(c) 2000 - Bao Ma Technology Co., LTD
3
4|-----------------------------------------|
5| DIP2 DIP4  UM3567(YM2413)               |J 
6| DIP1 DIP3                               |A
7|           TA-A-901                      |M
8| EN-A-701  EN-A-801  U6295(OKI)          |M
9| EN-A-501  EN-A-601                      |A
10| EN-A-301  EN-A-401                      |
11|                                         |C
12|                   AIA90610              |O
13|                   BMC-68pin  AIA90423   |N
14|                   plcc (68k) BMC-160pin |N
15|                                         |E
16|                                    OSC  |C
17|                                 42.000  |T
18|-----------------------------------------|
19
201 - BMC AIA90423 - 160-Pin ASIC, FGPA, Video?
211 - BMC AIA90610 - 68 Pin CPU (Likely 16 MHz, 68-lead plastic LCC 68000)
221 - UM3567 (YM2413) Sound
231 - U6295 (OKI6295) Sound
241 - 42.000MHz XTAL
254 - 8 Position DIP switches
26
27JAMMA CONNECTOR
28Component Side   A   B   Solder Side
29           GND   1   1   GND
30           GND   2   2   GND
31           +5v   3   3   +5v
32           +5v   4   4   +5v
33                 5   5
34          +12v   6   6   +12v
35                 7   7
36    Coin Meter   8   8
37                 9   9
38       Speaker  10   10  GND
39                11   11
40           Red  12   12  Green
41          Blue  13   13  Syn
42           GND  14   14
43          Test  15   15
44         Coin1  16   16  Coin2
45      1P Start  17   17  2P Start
46         1P Up  18   18  2P Up
47       1P Down  19   19  2P Down
48       1P Left  20   20  2P Left
49      1P Right  21   21  2P Right
50          1P A  22   22  2P A
51          1P B  23   23  2P B
52          1P C  24   24  2P C
53                25   25
54                26   26
55           GND  27   27  GND
56           GND  28   28  GND
57*/
58
59// looks like some kind of blitter
60// IGS-like?
61
62#include "emu.h"
63#include "cpu/m68000/m68000.h"
64#include "sound/okim6295.h"
65#include "sound/2413intf.h"
66
67class popobear_state : public driver_device
68{
69public:
70   popobear_state(const machine_config &mconfig, device_type type, const char *tag)
71      : driver_device(mconfig, type, tag),
72      m_maincpu(*this,"maincpu")
73      { }
74
75
76   UINT16 *popobear_vram;
77   required_device<cpu_device> m_maincpu;
78};
79
80/* stub read handlers */
81
82static READ16_HANDLER( popo_480001_r ) { static int i = 0x00;i ^=0xff;return i;}
83static READ16_HANDLER( popo_48001c_r ) { static int i = 0x00;i ^=0xff;return i;}
84static READ16_HANDLER( popo_480020_r ) { static int i = 0x00;i ^=0xff;return i;}
85static READ16_HANDLER( popo_48003a_r ) { static int i = 0x00;i ^=0xff;return i;}
86
87static READ16_HANDLER( popo_500000_r ) { static int i = 0x00;i ^=0xff;return i;}
88static READ16_HANDLER( popo_520000_r ) { static int i = 0x00;i ^=0xff;return i;}
89
90static READ16_HANDLER( popo_620000_r ) { static int i = 0x00;i ^=0xff;return i;}
91
92/* stub write handlers */
93
94static WRITE16_HANDLER( popo_480001_w ) { }
95static WRITE16_HANDLER( popo_480018_w ) { }
96static WRITE16_HANDLER( popo_48001a_w ) { }
97static WRITE16_HANDLER( popo_48001c_w ) { }
98static WRITE16_HANDLER( popo_480020_w ) { }
99static WRITE16_HANDLER( popo_480028_w ) { }
100static WRITE16_HANDLER( popo_48002c_w ) { }
101static WRITE16_HANDLER( popo_480030_w ) { }
102static WRITE16_HANDLER( popo_48003a_w ) { }
103
104static WRITE16_HANDLER( popo_550000_w ) { }
105static WRITE16_HANDLER( popo_550002_w ) { }
106
107static WRITE16_HANDLER( popo_600000_w ) { }
108static WRITE16_HANDLER( popo_620000_w ) { }
109
110
111static ADDRESS_MAP_START( popobear_mem, AS_PROGRAM, 16 )
112   AM_RANGE(0x000000, 0x03ffff) AM_ROM
113   AM_RANGE(0x210000, 0x21ffff) AM_RAM
114   AM_RANGE(0x3E0000, 0x3EFFFF) AM_RAM  AM_BASE_MEMBER(popobear_state, popobear_vram)
115
116   /* Blitter stuff? */
117   AM_RANGE(0x480000, 0x480001) AM_READ(popo_480001_r) AM_WRITE(popo_480001_w)
118   AM_RANGE(0x480018, 0x480019) AM_WRITE(popo_480018_w)
119   AM_RANGE(0x48001a, 0x48001b) AM_WRITE(popo_48001a_w)
120   AM_RANGE(0x48001c, 0x48001d) AM_READ(popo_48001c_r) AM_WRITE(popo_48001c_w)
121   AM_RANGE(0x480020, 0x480021) AM_READ(popo_480020_r) AM_WRITE(popo_480020_w)
122   AM_RANGE(0x480028, 0x480029) AM_WRITE(popo_480028_w)
123   AM_RANGE(0x48002c, 0x48002d) AM_WRITE(popo_48002c_w)
124   AM_RANGE(0x480030, 0x480031) AM_WRITE(popo_480030_w)
125   AM_RANGE(0x48003a, 0x48003b) AM_READ(popo_48003a_r) AM_WRITE(popo_48003a_w)
126
127   AM_RANGE(0x480400, 0x48041f) AM_RAM AM_WRITE(paletteram16_xRRRRRGGGGGBBBBB_word_w) AM_BASE_GENERIC(paletteram) // looks palette like at least
128   
129   /* I/O maybe? */
130   AM_RANGE(0x500000, 0x500001) AM_READ(popo_500000_r)
131   AM_RANGE(0x520000, 0x520001) AM_READ(popo_520000_r)
132   AM_RANGE(0x550000, 0x550001) AM_WRITE(popo_550000_w)
133   AM_RANGE(0x550002, 0x550003) AM_WRITE(popo_550002_w)
134
135   /* these could be where the OKI hooks up? */
136   AM_RANGE(0x600000, 0x600001) AM_WRITE(popo_600000_w)
137   AM_RANGE(0x620000, 0x620001) AM_READ(popo_620000_r) AM_WRITE(popo_620000_w)
138ADDRESS_MAP_END
139
140static INPUT_PORTS_START( popobear )
141
142   PORT_START("DSW1")
143   PORT_DIPNAME( 0x01, 0x01, DEF_STR( Demo_Sounds ) )
144   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
145   PORT_DIPSETTING(    0x01, DEF_STR( On ) )
146   PORT_DIPNAME( 0x0e, 0x00, "Coin_A" )
147   PORT_DIPSETTING(    0x0c, DEF_STR( 3C_1C ) )
148   PORT_DIPSETTING(    0x0a, DEF_STR( 2C_1C ) )
149   PORT_DIPSETTING(    0x00, DEF_STR( 1C_1C ) )
150   PORT_DIPSETTING(    0x02, DEF_STR( 1C_2C ) )
151   PORT_DIPSETTING(    0x04, DEF_STR( 1C_3C ) )
152   PORT_DIPSETTING(    0x06, DEF_STR( 1C_4C ) )
153   PORT_DIPSETTING(    0x08, DEF_STR( 1C_5C ) )
154   PORT_DIPSETTING(    0x0e, "Freeplay" )
155   PORT_DIPNAME( 0x30, 0x00, DEF_STR( Lives ) )
156   PORT_DIPSETTING(    0x10, "2" )
157   PORT_DIPSETTING(    0x00, "3" )
158   PORT_DIPSETTING(    0x20, "4" )
159   PORT_DIPSETTING(    0x30, "5" )
160   PORT_DIPNAME( 0xc0, 0x00, DEF_STR( Difficulty ) )
161   PORT_DIPSETTING(    0x80, DEF_STR( Very_Easy ) )
162   PORT_DIPSETTING(    0x40, DEF_STR( Easy ) )
163   PORT_DIPSETTING(    0x00, DEF_STR( Normal ) )
164   PORT_DIPSETTING(    0xc0, DEF_STR( Hard ) )
165
166   PORT_START("DSW2")
167   PORT_DIPNAME( 0x01, 0x00, "Arrow" )
168   PORT_DIPSETTING(    0x01, DEF_STR( No ) )
169   PORT_DIPSETTING(    0x00, DEF_STR( Yes ) )
170   PORT_DIPNAME( 0x02, 0x00, "DSW2:2" )
171   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
172   PORT_DIPSETTING(    0x02, DEF_STR( On ) )
173   PORT_DIPNAME( 0x04, 0x00, "DSW2:3" )
174   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
175   PORT_DIPSETTING(    0x04, DEF_STR( On ) )
176   PORT_DIPNAME( 0x08, 0x00, "DSW2:4" )
177   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
178   PORT_DIPSETTING(    0x08, DEF_STR( On ) )
179   PORT_DIPNAME( 0x10, 0x00, "DSW2:5" )
180   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
181   PORT_DIPSETTING(    0x10, DEF_STR( On ) )
182   PORT_DIPNAME( 0x20, 0x00, "DSW2:6" )
183   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
184   PORT_DIPSETTING(    0x20, DEF_STR( On ) )
185   PORT_DIPNAME( 0x40, 0x00, "DSW2:7" )
186   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
187   PORT_DIPSETTING(    0x40, DEF_STR( On ) )
188   PORT_DIPNAME( 0x80, 0x00, "DSW2:8" )
189   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
190   PORT_DIPSETTING(    0x80, DEF_STR( On ) )
191
192   PORT_START("DSW3")
193   PORT_DIPNAME( 0x01, 0x00, "DSW3:1" )
194   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
195   PORT_DIPSETTING(    0x01, DEF_STR( On ) )
196   PORT_DIPNAME( 0x02, 0x00, "DSW3:2" )
197   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
198   PORT_DIPSETTING(    0x02, DEF_STR( On ) )
199   PORT_DIPNAME( 0x04, 0x00, "DSW3:3" )
200   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
201   PORT_DIPSETTING(    0x04, DEF_STR( On ) )
202   PORT_DIPNAME( 0x08, 0x00, "DSW3:4" )
203   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
204   PORT_DIPSETTING(    0x08, DEF_STR( On ) )
205   PORT_DIPNAME( 0x10, 0x00, "DSW3:5" )
206   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
207   PORT_DIPSETTING(    0x10, DEF_STR( On ) )
208   PORT_DIPNAME( 0x20, 0x00, "DSW3:6" )
209   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
210   PORT_DIPSETTING(    0x20, DEF_STR( On ) )
211   PORT_DIPNAME( 0x40, 0x00, "DSW3:7" )
212   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
213   PORT_DIPSETTING(    0x40, DEF_STR( On ) )
214   PORT_DIPNAME( 0x80, 0x00, "DSW3:8" )
215   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
216   PORT_DIPSETTING(    0x80, DEF_STR( On ) )
217
218   PORT_START("DSW4")
219   PORT_DIPNAME( 0x01, 0x00, "DSW4:1" )
220   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
221   PORT_DIPSETTING(    0x01, DEF_STR( On ) )
222   PORT_DIPNAME( 0x02, 0x00, "DSW4:2" )
223   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
224   PORT_DIPSETTING(    0x02, DEF_STR( On ) )
225   PORT_DIPNAME( 0x04, 0x00, "DSW4:3" )
226   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
227   PORT_DIPSETTING(    0x04, DEF_STR( On ) )
228   PORT_DIPNAME( 0x08, 0x00, "DSW4:4" )
229   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
230   PORT_DIPSETTING(    0x08, DEF_STR( On ) )
231   PORT_DIPNAME( 0x10, 0x00, "DSW4:5" )
232   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
233   PORT_DIPSETTING(    0x10, DEF_STR( On ) )
234   PORT_DIPNAME( 0x20, 0x00, "DSW4:6" )
235   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
236   PORT_DIPSETTING(    0x20, DEF_STR( On ) )
237   PORT_DIPNAME( 0x40, 0x00, "DSW4:7" )
238   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
239   PORT_DIPSETTING(    0x40, DEF_STR( On ) )
240   PORT_DIPNAME( 0x80, 0x00, "DSW4:8" )
241   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
242   PORT_DIPSETTING(    0x80, DEF_STR( On ) )
243
244INPUT_PORTS_END
245
246
247static const gfx_layout tilelayout =
248{
249   4,8,
250   RGN_FRAC(1,1),
251   8,
252   { 0,1,2,3,4,5,6,7 },
253   { 24, 16, 8, 0 },
254   { 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32 },
255   8*32
256};
257
258// gfx don't seem to be tiles..
259static GFXDECODE_START( popobear )
260   GFXDECODE_ENTRY( "gfx1", 0, tilelayout,  0, 1 )
261   GFXDECODE_ENTRY( "gfx2", 0, tilelayout,  0, 1 )
262GFXDECODE_END
263
264
265SCREEN_UPDATE_IND16( popobear )
266{
267   popobear_state *state = screen.machine().driver_data<popobear_state>();
268   bitmap.fill(0, cliprect);
269
270   UINT16* popobear_vram = state->popobear_vram;
271   int count = 0;
272   for (int y=0;y<256;y++)
273   {
274      for (int x=0;x<128;x++)
275      {
276         UINT8 dat;
277         dat = (popobear_vram[count]&0xf000)>>12;
278         bitmap.pix16(y, (x*4)+0) =dat;
279
280         dat = (popobear_vram[count]&0x0f00)>>8;
281         bitmap.pix16(y, (x*4)+1) =dat;
282
283         dat = (popobear_vram[count]&0x00f0)>>4;
284         bitmap.pix16(y, (x*4)+2) =dat;
285
286         dat = (popobear_vram[count]&0x000f)>>0;
287         bitmap.pix16(y, (x*4)+3) =dat;
288
289         count++;
290      }
291   }
292
293   return 0;
294}
295
296VIDEO_START(popobear)
297{
298
299}
300
301static TIMER_DEVICE_CALLBACK( popobear_irq )
302{
303   popobear_state *state = timer.machine().driver_data<popobear_state>();
304   int scanline = param;
305
306   if(scanline == 240)
307      device_set_input_line(state->m_maincpu, 2, HOLD_LINE);
308
309   if(scanline == 128)
310      device_set_input_line(state->m_maincpu, 3, HOLD_LINE);
311
312   if(scanline == 32)
313      device_set_input_line(state->m_maincpu, 5, HOLD_LINE);
314}
315
316static MACHINE_CONFIG_START( popobear, popobear_state )
317   MCFG_CPU_ADD("maincpu", M68000, XTAL_42MHz/4)  // XTAL CORRECT, DIVISOR GUESSED
318   MCFG_CPU_PROGRAM_MAP(popobear_mem)
319   // levels 2,3,5 look interesting
320   //MCFG_CPU_VBLANK_INT("screen",irq3_line_hold)
321   MCFG_TIMER_ADD_SCANLINE("scantimer", popobear_irq, "screen", 0, 1)
322
323   MCFG_SCREEN_ADD("screen", RASTER)
324   MCFG_SCREEN_REFRESH_RATE(60)
325   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500)) /* not accurate */
326   MCFG_SCREEN_UPDATE_STATIC(popobear)
327
328   MCFG_GFXDECODE(popobear)
329
330   MCFG_SCREEN_SIZE(64*8, 32*8)
331   MCFG_SCREEN_VISIBLE_AREA(0*8, 64*8-1, 0*8, 32*8-1)
332   MCFG_PALETTE_LENGTH(256)
333
334   MCFG_VIDEO_START(popobear)
335
336   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
337
338   MCFG_SOUND_ADD("ym2413", YM2413, XTAL_42MHz/10)  // XTAL CORRECT, DIVISOR GUESSED
339   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "lspeaker", 1.00)
340   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "rspeaker", 1.00)
341
342   MCFG_OKIM6295_ADD("oki", XTAL_42MHz/10/4, OKIM6295_PIN7_LOW)  // XTAL CORRECT, DIVISOR GUESSED
343   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "lspeaker", 0.50)
344   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "rspeaker", 0.50)
345MACHINE_CONFIG_END
346
347
348ROM_START( popobear )
349   ROM_REGION( 0x400000, "maincpu", 0 ) /* 68000 Code */
350   ROM_LOAD16_BYTE( "popobear_en-a-301_1.6.u3", 0x000001, 0x20000, CRC(b934adf6) SHA1(93431c7a19af812b549aad35cc1176a81805ffab) )
351   ROM_LOAD16_BYTE( "popobear_en-a-401_1.6.u4", 0x000000, 0x20000, CRC(0568af9c) SHA1(920531dbc4bbde2d1db062bd5c48b97dd50b7185) )
352
353   ROM_REGION( 0x200000, "gfx1", 0 )
354   ROM_LOAD16_BYTE(   "popobear_en-a-501.u5", 0x000000, 0x100000, CRC(185901a9) SHA1(7ff82b5751645df53435eaa66edce589684cc5c7) )
355   ROM_LOAD16_BYTE(   "popobear_en-a-601.u6", 0x000001, 0x100000, CRC(84fa9f3f) SHA1(34dd7873f88b0dae5fb81fe84e82d2b6b49f7332) )
356
357   ROM_REGION( 0x200000, "gfx2", 0 )
358   ROM_LOAD16_BYTE(   "popobear_en-a-701.u7", 0x000000, 0x100000, CRC(45eba6d0) SHA1(0278602ed57ac45040619d590e6cc85e2cfeed31) )
359   ROM_LOAD16_BYTE(   "popobear_en-a-801.u8", 0x000001, 0x100000, CRC(2760f2e6) SHA1(58af59f486c9df930f7c124f89154f8f389a5bd7) )
360
361   ROM_REGION( 0x040000, "oki", 0 ) /* Samples */
362   ROM_LOAD( "popobear_ta-a-901.u9", 0x00000, 0x40000,  CRC(f1e94926) SHA1(f4d6f5b5811d90d0069f6efbb44d725ff0d07e1c) )
363ROM_END
364
365GAME( 2000, popobear,    0, popobear,    popobear,    0, ROT0,  "BMC", "PoPo Bear", GAME_NOT_WORKING | GAME_IS_SKELETON )
src/mame/drivers/galpanic.c
r14134r14135
127127
128128static SCREEN_VBLANK( galpanic )
129129{
130   // rising edge
131   if (vblank_on)
130   // falling edge
131   if (!vblank_on)
132132   {
133133      device_t *pandora = screen.machine().device("pandora");
134134      pandora_eof(pandora);
src/mame/drivers/bbusters.c
r14134r14135
700700   MCFG_NVRAM_ADD_0FILL("eeprom")
701701
702702   /* video hardware */
703   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM)
703   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
704704
705705   MCFG_SCREEN_ADD("screen", RASTER)
706706   MCFG_SCREEN_REFRESH_RATE(60)
r14134r14135
737737   MCFG_CPU_IO_MAP(sounda_portmap)
738738
739739   /* video hardware */
740   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM)
740   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
741741
742742   MCFG_SCREEN_ADD("screen", RASTER)
743743   MCFG_SCREEN_REFRESH_RATE(60)
src/mame/drivers/dreamwld.c
r14134r14135
585585   MCFG_MACHINE_RESET(dreamwld)
586586
587587   /* video hardware */
588   MCFG_VIDEO_ATTRIBUTES(VIDEO_UPDATE_AFTER_VBLANK)
589
588590   MCFG_SCREEN_ADD("screen", RASTER)
589591   MCFG_SCREEN_REFRESH_RATE(58)
590592   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500))
src/mame/drivers/gberet.c
r14134r14135
1515    gberetb is a bootleg hacked to run on different hardware.
1616
1717    TODO
18        - Original Green Beret is currently running too fast so it was downgraded to an unlikely
19          refresh rate (30 Hz). Possible causes ranges from irq sources not understood (there's a custom
20          IC that controls irq timings) or even waitstates (see MT #3600).
21        - Dump Green Beret Bootleg proms.  Bootleg has four proms while the original has three
22          and correct the locations.
18        - Measure IRQ and NMI frequency (of an original board), is IRQ really tied to the same timer that triggers NMI?
19        - Dump Green Beret Bootleg proms and correct the locations. Bootleg has four proms while the original has three.
2320        - Dump Green Beret Bootleg PAL
24        - Green Beret bootleg xtal is 20.000 MHz
2521
2622****************************************************************************
2723
r14134r14135
7066
7167    Interrupts
7268
73    The game uses both IRQ (mode 1) and NMI.
69    The game uses both IRQ (mode 1) and NMI via a custom interrupt controller.
7470
7571***************************************************************************/
7672
r14134r14135
8076#include "includes/konamipt.h"
8177#include "includes/gberet.h"
8278
83#define MASTER_CLOCK XTAL_18_432MHz
84
8579/*************************************
8680 *
8781 *  Interrupt generators
8882 *
8983 *************************************/
9084
91static TIMER_DEVICE_CALLBACK( gberet_scanline )
85static TIMER_DEVICE_CALLBACK( gberet_interrupt_tick )
9286{
9387   gberet_state *state = timer.machine().driver_data<gberet_state>();
94   int scanline = param;
88   UINT8 ticks_mask = ~state->m_interrupt_ticks & (state->m_interrupt_ticks + 1); // 0->1
89   state->m_interrupt_ticks++;
9590
96   if(scanline == 240)
97   {
98      if (state->m_irq_enable)
99         cputag_set_input_line(timer.machine(), "maincpu", 0, HOLD_LINE);
100   }
101   else if ((scanline % 16) == 0)
102   {
103      if (state->m_nmi_enable)
104         cputag_set_input_line(timer.machine(), "maincpu", INPUT_LINE_NMI, PULSE_LINE);
105   }
106}
91   // NMI on d0
92   if (ticks_mask & state->m_interrupt_mask & 1)
93      cputag_set_input_line(timer.machine(), "maincpu", INPUT_LINE_NMI, ASSERT_LINE);
94   
95   // IRQ on d3 (used by mrgoemon)
96   if (ticks_mask & state->m_interrupt_mask<<2 & 8)
97      cputag_set_input_line(timer.machine(), "maincpu", 0, ASSERT_LINE);
10798
108static TIMER_DEVICE_CALLBACK( mrgoemon_scanline )
109{
110   gberet_state *state = timer.machine().driver_data<gberet_state>();
111   int scanline = param;
112
113   if(scanline == 240)
114   {
115      if (state->m_irq_enable)
116         cputag_set_input_line(timer.machine(), "maincpu", 0, HOLD_LINE);
117   }
118   else if ((scanline % 32) == 0)
119   {
120      if (state->m_nmi_enable)
121         cputag_set_input_line(timer.machine(), "maincpu", INPUT_LINE_NMI, PULSE_LINE);
122   }
99   // IRQ on d4 (used by gberet)
100   if (ticks_mask & state->m_interrupt_mask<<2 & 16)
101      cputag_set_input_line(timer.machine(), "maincpu", 0, ASSERT_LINE);
123102}
124103
125104
126105/*************************************
127106 *
128 *  Memory handlers
107 *  Address maps / Memory handlers
129108 *
130109 *************************************/
131110
132111static WRITE8_HANDLER( gberet_coin_counter_w )
133112{
134113   /* bits 0/1 = coin counters */
135   coin_counter_w(space->machine(), 0, data & 0x01);
136   coin_counter_w(space->machine(), 1, data & 0x02);
114   coin_counter_w(space->machine(), 0, data & 1);
115   coin_counter_w(space->machine(), 1, data & 2);
137116}
138117
139static WRITE8_HANDLER( gberet_flipscreen_w )
140{
141   gberet_state *state = space->machine().driver_data<gberet_state>();
142   state->m_nmi_enable = data & 0x01;
143   state->m_irq_enable = data & 0x04;
144
145   flip_screen_set(space->machine(), data & 0x08);
146}
147
148118static WRITE8_HANDLER( mrgoemon_coin_counter_w )
149119{
150120   /* bits 0/1 = coin counters */
151   coin_counter_w(space->machine(), 0, data & 0x01);
152   coin_counter_w(space->machine(), 1, data & 0x02);
121   coin_counter_w(space->machine(), 0, data & 1);
122   coin_counter_w(space->machine(), 1, data & 2);
153123
154124   /* bits 5-7 = ROM bank select */
155125   memory_set_bank(space->machine(), "bank1", ((data & 0xe0) >> 5));
156126}
157127
158static WRITE8_HANDLER( mrgoemon_flipscreen_w )
128static WRITE8_HANDLER( gberet_flipscreen_w )
159129{
160130   gberet_state *state = space->machine().driver_data<gberet_state>();
161   state->m_nmi_enable = data & 0x01;
162   state->m_irq_enable = data & 0x02;
163131
164   flip_screen_set(space->machine(), data & 0x08);
132   /* bits 0/1/2 = interrupt enable */
133   UINT8 ack_mask = ~data & state->m_interrupt_mask; // 1->0
134
135   if (ack_mask & 1)
136      cputag_set_input_line(space->machine(), "maincpu", INPUT_LINE_NMI, CLEAR_LINE);
137
138   if (ack_mask & 6)
139      cputag_set_input_line(space->machine(), "maincpu", 0, CLEAR_LINE);
140
141   state->m_interrupt_mask = data & 7;
142
143   /* bit 3 = flip screen */
144   flip_screen_set(space->machine(), data & 8);
165145}
166146
167/*************************************
168 *
169 *  Address maps
170 *
171 *************************************/
147static WRITE8_HANDLER( gberet_sound_w )
148{
149   gberet_state *state = space->machine().driver_data<gberet_state>();
150   sn76496_w(space->machine().device("snsnd"), 0, *state->m_soundlatch);
151}
172152
173153static ADDRESS_MAP_START( gberet_map, AS_PROGRAM, 8 )
174154   AM_RANGE(0x0000, 0xbfff) AM_ROM
r14134r14135
182162   AM_RANGE(0xe043, 0xe043) AM_WRITE(gberet_sprite_bank_w)
183163   AM_RANGE(0xe044, 0xe044) AM_WRITE(gberet_flipscreen_w)
184164   AM_RANGE(0xf000, 0xf000) AM_WRITE(gberet_coin_counter_w)
185   AM_RANGE(0xf200, 0xf200) AM_READ_PORT("DSW2") AM_WRITENOP         // Loads the snd command into the snd latch
186   AM_RANGE(0xf400, 0xf400) AM_READ_PORT("DSW3") AM_DEVWRITE("snsnd", sn76496_w)   // This address triggers the SN chip to read the data port.
187   AM_RANGE(0xf600, 0xf600) AM_READ_PORT("DSW1")
165   AM_RANGE(0xf200, 0xf200) AM_READ_PORT("DSW2") AM_WRITEONLY AM_BASE_MEMBER(gberet_state, m_soundlatch)
166   AM_RANGE(0xf400, 0xf400) AM_READ_PORT("DSW3") AM_WRITE(gberet_sound_w)
167   AM_RANGE(0xf600, 0xf600) AM_READ_PORT("DSW1") AM_WRITE(watchdog_reset_w)
188168   AM_RANGE(0xf601, 0xf601) AM_READ_PORT("P2")
189169   AM_RANGE(0xf602, 0xf602) AM_READ_PORT("P1")
190170   AM_RANGE(0xf603, 0xf603) AM_READ_PORT("SYSTEM")
191   AM_RANGE(0xf600, 0xf600) AM_WRITE(watchdog_reset_w)
192171ADDRESS_MAP_END
193172
173static ADDRESS_MAP_START( mrgoemon_map, AS_PROGRAM, 8 )
174   AM_RANGE(0x0000, 0xbfff) AM_ROM
175   AM_RANGE(0xc000, 0xc7ff) AM_RAM_WRITE(gberet_colorram_w) AM_BASE_MEMBER(gberet_state, m_colorram)
176   AM_RANGE(0xc800, 0xcfff) AM_RAM_WRITE(gberet_videoram_w) AM_BASE_MEMBER(gberet_state, m_videoram)
177   AM_RANGE(0xd000, 0xd0ff) AM_RAM AM_BASE_MEMBER(gberet_state, m_spriteram2)
178   AM_RANGE(0xd100, 0xd1ff) AM_RAM AM_BASE_MEMBER(gberet_state, m_spriteram)
179   AM_RANGE(0xd200, 0xdfff) AM_RAM
180   AM_RANGE(0xe000, 0xe03f) AM_RAM_WRITE(gberet_scroll_w) AM_BASE_MEMBER(gberet_state, m_scrollram)
181   AM_RANGE(0xe040, 0xe042) AM_WRITENOP // ???
182   AM_RANGE(0xe043, 0xe043) AM_WRITE(gberet_sprite_bank_w)
183   AM_RANGE(0xe044, 0xe044) AM_WRITE(gberet_flipscreen_w)
184   AM_RANGE(0xf000, 0xf000) AM_WRITE(mrgoemon_coin_counter_w)
185   AM_RANGE(0xf200, 0xf200) AM_READ_PORT("DSW2") AM_WRITEONLY AM_BASE_MEMBER(gberet_state, m_soundlatch)
186   AM_RANGE(0xf400, 0xf400) AM_READ_PORT("DSW3") AM_WRITE(gberet_sound_w)
187   AM_RANGE(0xf600, 0xf600) AM_READ_PORT("DSW1") AM_WRITE(watchdog_reset_w)
188   AM_RANGE(0xf601, 0xf601) AM_READ_PORT("P2")
189   AM_RANGE(0xf602, 0xf602) AM_READ_PORT("P1")
190   AM_RANGE(0xf603, 0xf603) AM_READ_PORT("SYSTEM")
191   AM_RANGE(0xf800, 0xffff) AM_ROMBANK("bank1")
192ADDRESS_MAP_END
193
194
195static WRITE8_HANDLER( gberetb_flipscreen_w )
196{
197   flip_screen_set(space->machine(), data & 8);
198}
199
200static READ8_HANDLER( gberetb_irq_ack_r )
201{
202   cputag_set_input_line(space->machine(), "maincpu", 0, CLEAR_LINE);
203   return 0xff;
204}
205
206static WRITE8_HANDLER( gberetb_nmi_ack_w )
207{
208   cputag_set_input_line(space->machine(), "maincpu", INPUT_LINE_NMI, CLEAR_LINE);
209}
210
194211static ADDRESS_MAP_START( gberetb_map, AS_PROGRAM, 8 )
195212   AM_RANGE(0x0000, 0xbfff) AM_ROM
196213   AM_RANGE(0xc000, 0xc7ff) AM_RAM_WRITE(gberet_colorram_w) AM_BASE_MEMBER(gberet_state, m_colorram)
r14134r14135
198215   AM_RANGE(0xd000, 0xdfff) AM_RAM
199216   AM_RANGE(0xe000, 0xe03f) AM_RAM
200217   AM_RANGE(0xe040, 0xe043) AM_WRITENOP // ???
201   AM_RANGE(0xe044, 0xe044) AM_WRITE(gberet_flipscreen_w)
218   AM_RANGE(0xe044, 0xe044) AM_WRITE(gberetb_flipscreen_w) // did hw even support flipscreen?
202219   AM_RANGE(0xe800, 0xe8ff) AM_RAM
203220   AM_RANGE(0xe900, 0xe9ff) AM_RAM AM_BASE_SIZE_MEMBER(gberet_state, m_spriteram, m_spriteram_size)
204   AM_RANGE(0xf000, 0xf000) AM_WRITENOP            // coin counter not supported
221   AM_RANGE(0xf000, 0xf000) AM_WRITENOP // coin counter not supported
205222   AM_RANGE(0xf200, 0xf200) AM_READ_PORT("DSW2")
206223   AM_RANGE(0xf400, 0xf400) AM_DEVWRITE("snsnd", sn76496_w)
207224   AM_RANGE(0xf600, 0xf600) AM_READ_PORT("P2")
208225   AM_RANGE(0xf601, 0xf601) AM_READ_PORT("DSW1")
209226   AM_RANGE(0xf602, 0xf602) AM_READ_PORT("P1")
210227   AM_RANGE(0xf603, 0xf603) AM_READ_PORT("SYSTEM")
211   AM_RANGE(0xf800, 0xf800) AM_NOP                  // IRQ/NMI acknowledge
228   AM_RANGE(0xf800, 0xf800) AM_READWRITE(gberetb_irq_ack_r, gberetb_nmi_ack_w)
212229   AM_RANGE(0xf900, 0xf901) AM_WRITE(gberetb_scroll_w)
213230ADDRESS_MAP_END
214231
215static ADDRESS_MAP_START( mrgoemon_map, AS_PROGRAM, 8 )
216   AM_RANGE(0x0000, 0xbfff) AM_ROM
217   AM_RANGE(0xc000, 0xc7ff) AM_RAM_WRITE(gberet_colorram_w) AM_BASE_MEMBER(gberet_state, m_colorram)
218   AM_RANGE(0xc800, 0xcfff) AM_RAM_WRITE(gberet_videoram_w) AM_BASE_MEMBER(gberet_state, m_videoram)
219   AM_RANGE(0xd000, 0xd0ff) AM_RAM AM_BASE_MEMBER(gberet_state, m_spriteram2)
220   AM_RANGE(0xd100, 0xd1ff) AM_RAM AM_BASE_MEMBER(gberet_state, m_spriteram)
221   AM_RANGE(0xd200, 0xdfff) AM_RAM
222   AM_RANGE(0xe000, 0xe03f) AM_RAM_WRITE(gberet_scroll_w) AM_BASE_MEMBER(gberet_state, m_scrollram)
223   AM_RANGE(0xe040, 0xe042) AM_WRITENOP // ???
224   AM_RANGE(0xe043, 0xe043) AM_WRITE(gberet_sprite_bank_w)
225   AM_RANGE(0xe044, 0xe044) AM_WRITE(mrgoemon_flipscreen_w)
226   AM_RANGE(0xf000, 0xf000) AM_WRITE(mrgoemon_coin_counter_w)
227   AM_RANGE(0xf200, 0xf200) AM_READ_PORT("DSW2") AM_WRITENOP            // Loads the snd command into the snd latch
228   AM_RANGE(0xf400, 0xf400) AM_READ_PORT("DSW3") AM_DEVWRITE("snsnd", sn76496_w)      // This address triggers the SN chip to read the data port.
229   AM_RANGE(0xf600, 0xf600) AM_READ_PORT("DSW1") AM_WRITE(watchdog_reset_w)
230   AM_RANGE(0xf601, 0xf601) AM_READ_PORT("P2")
231   AM_RANGE(0xf602, 0xf602) AM_READ_PORT("P1")
232   AM_RANGE(0xf603, 0xf603) AM_READ_PORT("SYSTEM")
233   AM_RANGE(0xf800, 0xffff) AM_ROMBANK("bank1")
234ADDRESS_MAP_END
235232
236233/*************************************
237234 *
r14134r14135
241238
242239static INPUT_PORTS_START( gberet )
243240   PORT_START("P1")
244   KONAMI8_MONO_B12_UNK               // button 1 = knife, button 2 = shoot
241   KONAMI8_MONO_B12_UNK
245242
246243   PORT_START("P2")
247244   KONAMI8_COCKTAIL_B12_UNK
r14134r14135
256253   PORT_START("DSW2")
257254   PORT_DIPNAME( 0x03, 0x02, DEF_STR( Lives ) )      PORT_DIPLOCATION("SW2:1,2")
258255   PORT_DIPSETTING(    0x03, "2" )
259   PORT_DIPSETTING(    0x02, "3" )      // factory default
256   PORT_DIPSETTING(    0x02, "3" )
260257   PORT_DIPSETTING(    0x01, "5" )
261258   PORT_DIPSETTING(    0x00, "7" )
262259   PORT_DIPNAME( 0x04, 0x00, DEF_STR( Cabinet ) )      PORT_DIPLOCATION("SW2:3")
r14134r14135
264261   PORT_DIPSETTING(    0x04, DEF_STR( Cocktail ) )
265262   PORT_DIPNAME( 0x18, 0x08, DEF_STR( Bonus_Life ) )   PORT_DIPLOCATION("SW2:4,5")
266263   PORT_DIPSETTING(    0x18, "30K, 70K, Every 70K" )
267   PORT_DIPSETTING(    0x10, "40K, 80K, Every 80K" )      // Japanese default
268   PORT_DIPSETTING(    0x08, "50K, 100K, Every 100K" )      // US default
264   PORT_DIPSETTING(    0x10, "40K, 80K, Every 80K" )   // Japanese default
265   PORT_DIPSETTING(    0x08, "50K, 100K, Every 100K" )   // US default
269266   PORT_DIPSETTING(    0x00, "50K, 200K, Every 200K" )
270267   PORT_DIPNAME( 0x60, 0x40, DEF_STR( Difficulty ) )   PORT_DIPLOCATION("SW2:6,7")
271268   PORT_DIPSETTING(    0x60, DEF_STR( Easy ) )
272   PORT_DIPSETTING(    0x40, DEF_STR( Normal ) )         // factory default
269   PORT_DIPSETTING(    0x40, DEF_STR( Normal ) )
273270   PORT_DIPSETTING(    0x20, DEF_STR( Difficult ) )
274271   PORT_DIPSETTING(    0x00, DEF_STR( Very_Difficult ) )
275272   PORT_DIPNAME( 0x80, 0x00, DEF_STR( Demo_Sounds ) )   PORT_DIPLOCATION("SW2:8")
r14134r14135
309306
310307   PORT_MODIFY("DSW2")
311308   PORT_DIPNAME( 0x18, 0x18, DEF_STR( Bonus_Life ) )   PORT_DIPLOCATION("SW2:4,5")
312   PORT_DIPSETTING(    0x18, "20K, Every 60K" )   // factory default
309   PORT_DIPSETTING(    0x18, "20K, Every 60K" )
313310   PORT_DIPSETTING(    0x10, "30K, Every 70K" )
314311   PORT_DIPSETTING(    0x08, "40K, Every 80K" )
315312   PORT_DIPSETTING(    0x00, "50K, Every 90K" )
r14134r14135
318315   PORT_SERVICE_DIPLOC(   0x04, IP_ACTIVE_LOW, "SW3:3" )
319316INPUT_PORTS_END
320317
318
321319/*************************************
322320 *
323321 *  Graphics definitions
r14134r14135
385383
386384/*************************************
387385 *
388 *  Machine driver
386 *  Machine drivers
389387 *
390388 *************************************/
391389
r14134r14135
393391{
394392   gberet_state *state = machine.driver_data<gberet_state>();
395393
396   state->save_item(NAME(state->m_irq_enable));
397   state->save_item(NAME(state->m_nmi_enable));
394   state->save_item(NAME(state->m_interrupt_mask));
395   state->save_item(NAME(state->m_interrupt_ticks));
398396   state->save_item(NAME(state->m_spritebank));
399397}
400398
r14134r14135
402400{
403401   gberet_state *state = machine.driver_data<gberet_state>();
404402
405   state->m_irq_enable = 0;
406   state->m_nmi_enable = 0;
403   state->m_interrupt_mask = 0;
404   state->m_interrupt_ticks = 0;
407405   state->m_spritebank = 0;
408406}
409407
410408static MACHINE_CONFIG_START( gberet, gberet_state )
411409
412410   /* basic machine hardware */
413   MCFG_CPU_ADD("maincpu", Z80, MASTER_CLOCK/6)   // X1S (generated by a custom IC)
411   MCFG_CPU_ADD("maincpu", Z80, XTAL_18_432MHz/6)      // X1S (generated by a custom IC)
414412   MCFG_CPU_PROGRAM_MAP(gberet_map)
415   MCFG_TIMER_ADD_SCANLINE("scantimer", gberet_scanline, "screen", 0, 1)
413   MCFG_TIMER_ADD_SCANLINE("scantimer", gberet_interrupt_tick, "screen", 0, 16) // ?
416414
417415   MCFG_MACHINE_START(gberet)
418416   MCFG_MACHINE_RESET(gberet)
419417
420418   /* video hardware */
421419   MCFG_SCREEN_ADD("screen", RASTER)
422   MCFG_SCREEN_REFRESH_RATE(30)
420   MCFG_SCREEN_REFRESH_RATE(60.60)
423421   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0))
424422   MCFG_SCREEN_SIZE(32*8, 32*8)
425423   MCFG_SCREEN_VISIBLE_AREA(1*8, 31*8-1, 2*8, 30*8-1)
r14134r14135
434432   /* sound hardware */
435433   MCFG_SPEAKER_STANDARD_MONO("mono")
436434
437   MCFG_SOUND_ADD("snsnd", SN76489A, MASTER_CLOCK/12) /* type verified on real and bootleg pcb */
435   MCFG_SOUND_ADD("snsnd", SN76489A, XTAL_18_432MHz/12) /* type verified on real and bootleg pcb */
438436   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
439437MACHINE_CONFIG_END
440438
441static MACHINE_CONFIG_DERIVED( gberetb, gberet )
439static MACHINE_CONFIG_DERIVED( mrgoemon, gberet )
442440
443441   /* basic machine hardware */
444442   MCFG_CPU_MODIFY("maincpu")
443   MCFG_CPU_PROGRAM_MAP(mrgoemon_map)
444MACHINE_CONFIG_END
445
446static MACHINE_CONFIG_START( gberetb, gberet_state )
447
448   /* basic machine hardware */
449   MCFG_CPU_ADD("maincpu", Z80, XTAL_20MHz/4) // divider guessed
445450   MCFG_CPU_PROGRAM_MAP(gberetb_map)
446   MCFG_TIMER_MODIFY("scantimer")//, mrgoemon_scanline, "screen", 0, 1)
447   MCFG_TIMER_CALLBACK(mrgoemon_scanline)
451   MCFG_CPU_VBLANK_INT("screen", irq0_line_assert)
452   MCFG_CPU_PERIODIC_INT(nmi_line_assert, XTAL_20MHz/0x8000) // divider guessed
448453
454   MCFG_MACHINE_START(gberet)
455   MCFG_MACHINE_RESET(gberet)
456
449457   /* video hardware */
450   MCFG_SCREEN_MODIFY("screen")
458   MCFG_SCREEN_ADD("screen", RASTER)
451459   MCFG_SCREEN_REFRESH_RATE(60)
460   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0))
461   MCFG_SCREEN_SIZE(32*8, 32*8)
462   MCFG_SCREEN_VISIBLE_AREA(1*8, 31*8-1, 2*8, 30*8-1)
452463   MCFG_SCREEN_UPDATE_STATIC(gberetb)
453464
454465   MCFG_GFXDECODE(gberetb)
455MACHINE_CONFIG_END
466   MCFG_PALETTE_LENGTH(2*16*16)
456467
457static MACHINE_CONFIG_DERIVED( mrgoemon, gberet )
468   MCFG_PALETTE_INIT(gberet)
469   MCFG_VIDEO_START(gberet)
458470
459   /* basic machine hardware */
460   MCFG_CPU_MODIFY("maincpu")
461   MCFG_CPU_PROGRAM_MAP(mrgoemon_map)
462   MCFG_TIMER_MODIFY("scantimer")//, mrgoemon_scanline, "screen", 0, 1)
463   MCFG_TIMER_CALLBACK(mrgoemon_scanline)
471   /* sound hardware */
472   MCFG_SPEAKER_STANDARD_MONO("mono")
464473
465   MCFG_SCREEN_MODIFY("screen")
466   MCFG_SCREEN_REFRESH_RATE(60)
474   MCFG_SOUND_ADD("snsnd", SN76489A, XTAL_20MHz/12) // divider guessed
475   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
467476MACHINE_CONFIG_END
468477
478
469479/*************************************
470480 *
471481 *  ROM definition(s)
r14134r14135
569579   memory_configure_bank(machine, "bank1", 0, 8, &ROM[0x10000], 0x800);
570580}
571581
582
572583/*************************************
573584 *
574 *  Game driver(s)
585 *  Game drivers
575586 *
576587 *************************************/
577588
src/mame/drivers/sandscrp.c
r14134r14135
136136
137137static SCREEN_VBLANK( sandscrp )
138138{
139   // rising edge
140   if (vblank_on)
139   // falling edge
140   if (!vblank_on)
141141   {
142142      sandscrp_state *state = screen.machine().driver_data<sandscrp_state>();
143143      device_t *pandora = screen.machine().device("pandora");
src/mame/drivers/gts80a.c
r14134r14135
661661/* cust  */GAME(1983,   krullp,      0,      gts80a_ss,   gts80a,   gts80a,   ROT0,   "Gottlieb",      "Krull (Pinball)",            GAME_IS_SKELETON_MECHANICAL)
662662/* disp3 */GAME(1982,   punk,      0,      gts80a_ss,   gts80a,   gts80a,   ROT0,   "Gottlieb",      "Punk!",            GAME_IS_SKELETON_MECHANICAL)
663663/* disp3 */GAME(1983,   qbquest,   0,      gts80a_ss,   gts80a,   gts80a,   ROT0,   "Gottlieb",      "Q*Bert's Quest",         GAME_IS_SKELETON_MECHANICAL)
664/* disp3 */GAME(1983,   rackempp,   0,      gts80a_s,   gts80a,   gts80a,   ROT0,   "Gottlieb",      "Rack 'Em Up (Pinball)",         GAME_IS_SKELETON_MECHANICAL)
664/* disp3 */GAME(1983,   rackempp,   0,      gts80a_s,   gts80a,   gts80a,   ROT0,   "Gottlieb",      "Rack 'em Up! (Pinball)",         GAME_IS_SKELETON_MECHANICAL)
665665/* disp3 */GAME(1983,   raimfire,   0,      gts80a_s,   gts80a,   gts80a,   ROT0,   "Gottlieb",      "Ready...Aim...Fire!",      GAME_IS_SKELETON_MECHANICAL)
666666/* cust  */GAME(1982,   rocky,      0,      gts80a_ss,   gts80a,   gts80a,   ROT0,   "Gottlieb",      "Rocky",            GAME_IS_SKELETON_MECHANICAL)
667667/* disp3 */GAME(1983,   rflshdlx,   0,      gts80a_ss,   gts80a,   gts80a,   ROT0,   "Gottlieb",      "Royal Flush Deluxe",      GAME_IS_SKELETON_MECHANICAL)
src/mame/drivers/twin16.c
r14134r14135
746746   MCFG_MACHINE_RESET(twin16)
747747
748748   // video hardware
749   MCFG_VIDEO_ATTRIBUTES(VIDEO_HAS_SHADOWS | VIDEO_BUFFERS_SPRITERAM)
749   MCFG_VIDEO_ATTRIBUTES(VIDEO_HAS_SHADOWS | VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
750750
751751   MCFG_SCREEN_ADD("screen", RASTER)
752752   MCFG_SCREEN_REFRESH_RATE(((double)XTAL_18_432MHz / 2) / (576 * 264))
r14134r14135
799799   MCFG_MACHINE_RESET(twin16)
800800
801801   /* video hardware */
802   MCFG_VIDEO_ATTRIBUTES(VIDEO_HAS_SHADOWS | VIDEO_BUFFERS_SPRITERAM)
802   MCFG_VIDEO_ATTRIBUTES(VIDEO_HAS_SHADOWS | VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
803803
804804   MCFG_SCREEN_ADD("screen", RASTER)
805805   MCFG_SCREEN_REFRESH_RATE(60)
src/mame/drivers/dec8.c
r14134r14135
20652065   MCFG_MACHINE_RESET(dec8)
20662066
20672067   /* video hardware */
2068   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM)
2068   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
20692069
20702070   MCFG_DEVICE_ADD("tilegen1", DECO_BAC06, 0)
20712071   deco_bac06_device::set_gfx_region_wide(*device, 2,2,0);
r14134r14135
22172217   MCFG_MACHINE_RESET(dec8)
22182218
22192219   /* video hardware */
2220   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM)
2220   MCFG_VIDEO_ATTRIBUTES(VIDEO_BUFFERS_SPRITERAM | VIDEO_UPDATE_AFTER_VBLANK)
22212221
22222222   MCFG_DEVICE_ADD("spritegen", DECO_KARNOVSPRITES, 0)
22232223   deco_karnovsprites_device::set_gfx_region(*device, 1);
src/mame/drivers/asuka.c
r14134r14135
819819
820820static const pc090oj_interface asuka_pc090oj_intf =
821821{
822   0, 0, 8,
822   0, 0, 8, 1
823823};
824824
825static const pc090oj_interface cadash_pc090oj_intf =
825static const pc090oj_interface bonzeadv_pc090oj_intf =
826826{
827   0, 0, 8, 1
827   0, 0, 8,
828828};
829829
830830static const tc0110pcr_interface asuka_tc0110pcr_intf =
r14134r14135
876876
877877static SCREEN_VBLANK( asuka )
878878{
879   if (vblank_on)
879   if (!vblank_on)
880880   {
881881      asuka_state *state = screen.machine().driver_data<asuka_state>();
882882      pc090oj_eof_callback(state->m_pc090oj);
r14134r14135
922922   MCFG_GFXDECODE(asuka)
923923   MCFG_PALETTE_LENGTH(4096)
924924
925   MCFG_PC090OJ_ADD("pc090oj", asuka_pc090oj_intf)
925   MCFG_PC090OJ_ADD("pc090oj", bonzeadv_pc090oj_intf)
926926   MCFG_TC0100SCN_ADD("tc0100scn", asuka_tc0100scn_intf)
927927   MCFG_TC0110PCR_ADD("tc0110pcr", asuka_tc0110pcr_intf)
928928
r14134r14135
10191019   MCFG_GFXDECODE(asuka)
10201020   MCFG_PALETTE_LENGTH(4096)
10211021
1022   MCFG_PC090OJ_ADD("pc090oj", cadash_pc090oj_intf)
1022   MCFG_PC090OJ_ADD("pc090oj", asuka_pc090oj_intf)
10231023   MCFG_TC0100SCN_ADD("tc0100scn", cadash_tc0100scn_intf)
10241024   MCFG_TC0110PCR_ADD("tc0110pcr", asuka_tc0110pcr_intf)
10251025
r14134r14135
10631063   MCFG_GFXDECODE(asuka)
10641064   MCFG_PALETTE_LENGTH(4096)   /* only Mofflott uses full palette space */
10651065
1066   MCFG_PC090OJ_ADD("pc090oj", asuka_pc090oj_intf)
1066   MCFG_PC090OJ_ADD("pc090oj", bonzeadv_pc090oj_intf)
10671067   MCFG_TC0100SCN_ADD("tc0100scn", cadash_tc0100scn_intf)
10681068   MCFG_TC0110PCR_ADD("tc0110pcr", asuka_tc0110pcr_intf)
10691069
r14134r14135
11111111   MCFG_GFXDECODE(asuka)
11121112   MCFG_PALETTE_LENGTH(4096)   /* only Mofflott uses full palette space */
11131113
1114   MCFG_PC090OJ_ADD("pc090oj", asuka_pc090oj_intf)
1114   MCFG_PC090OJ_ADD("pc090oj", bonzeadv_pc090oj_intf)
11151115   MCFG_TC0100SCN_ADD("tc0100scn", cadash_tc0100scn_intf)
11161116   MCFG_TC0110PCR_ADD("tc0110pcr", asuka_tc0110pcr_intf)
11171117
r14134r14135
11551155   MCFG_GFXDECODE(asuka)
11561156   MCFG_PALETTE_LENGTH(4096)
11571157
1158   MCFG_PC090OJ_ADD("pc090oj", asuka_pc090oj_intf)
1158   MCFG_PC090OJ_ADD("pc090oj", bonzeadv_pc090oj_intf)
11591159   MCFG_TC0100SCN_ADD("tc0100scn", cadash_tc0100scn_intf)
11601160   MCFG_TC0110PCR_ADD("tc0110pcr", asuka_tc0110pcr_intf)
11611161
src/mame/drivers/hvyunit.c
r14134r14135
171171
172172static SCREEN_VBLANK( hvyunit )
173173{
174   // rising edge
175   if (vblank_on)
174   // falling edge
175   if (!vblank_on)
176176   {
177177      hvyunit_state *state = screen.machine().driver_data<hvyunit_state>();
178178      pandora_eof(state->m_pandora);
src/tools/tools.mak
r14134r14135
8484CHDMANOBJS = \
8585   $(TOOLSOBJ)/chdman.o \
8686
87chdman$(EXE): $(VERSIONOBJ) $(CHDMANOBJS) $(LIBUTIL) $(ZLIB) $(EXPAT) $(LIBOCORE)
87chdman$(EXE): $(VERSIONOBJ) $(CHDMANOBJS) $(LIBUTIL) $(ZLIB) $(EXPAT) $(FLAC_LIB) $(LIBOCORE)
8888   @echo Linking $@...
89   $(LD) $(LDFLAGS) $^ $(LIBS) -o $@
89   $(LD) $(LDFLAGS) $^ $(LIBS) $(FLAC_LIB) -o $@
9090
9191
9292
r14134r14135
123123LDRESAMPLEOBJS = \
124124   $(TOOLSOBJ)/ldresample.o \
125125
126ldresample$(EXE): $(LDRESAMPLEOBJS) $(LIBUTIL) $(LIBOCORE) $(ZLIB) $(EXPAT)
126ldresample$(EXE): $(LDRESAMPLEOBJS) $(LIBUTIL) $(LIBOCORE) $(ZLIB) $(FLAC_LIB) $(EXPAT)
127127   @echo Linking $@...
128   $(LD) $(LDFLAGS) $^ $(LIBS) -o $@
128   $(LD) $(LDFLAGS) $^ $(LIBS) $(FLAC_LIB) -o $@
129129
130130
131131
r14134r14135
136136LDVERIFYOBJS = \
137137   $(TOOLSOBJ)/ldverify.o \
138138
139ldverify$(EXE): $(LDVERIFYOBJS) $(LIBUTIL) $(LIBOCORE) $(ZLIB) $(EXPAT)
139ldverify$(EXE): $(LDVERIFYOBJS) $(LIBUTIL) $(LIBOCORE) $(ZLIB) $(FLAC_LIB) $(EXPAT)
140140   @echo Linking $@...
141   $(LD) $(LDFLAGS) $^ $(LIBS) -o $@
141   $(LD) $(LDFLAGS) $^ $(LIBS) $(FLAC_LIB) -o $@
142142
143143
144144
src/tools/chdman.c
r14134r14135
717717      toc.tracks[i].extraframes = hunks * CD_FRAMES_PER_HUNK - toc.tracks[i].frames;
718718   }
719719
720
720721   /* count up the total number of frames */
721722   origtotalsectors = totalsectors = 0;
722723   for (i = 0; i < toc.numtrks; i++)
r14134r14135
727728   printf("\nCD-ROM %s has %d tracks and %d total frames\n", inputfile, toc.numtrks, origtotalsectors);
728729
729730   /* create the new CHD file */
730   err = chd_create(outputfile, (UINT64)totalsectors * (UINT64)sectorsize, hunksize, CHDCOMPRESSION_ZLIB_PLUS, NULL);
731   if (param) err = chd_create(outputfile, (UINT64)totalsectors * (UINT64)sectorsize, hunksize, CHDCOMPRESSION_ZLIB_PLUS_WITH_FLAC, NULL);
732   else err = chd_create(outputfile, (UINT64)totalsectors * (UINT64)sectorsize, hunksize, CHDCOMPRESSION_ZLIB_PLUS, NULL);
731733   if (err != CHDERR_NONE)
732734   {
733735      fprintf(stderr, "Error creating CHD file: %s\n", chd_error_string(err));
r14134r14135
816818            frames++;
817819         }
818820
821         int is_half_hunk = 0;
822         if ((curhunk == trackhunks-1) && (toc.tracks[i].extraframes>3))
823            is_half_hunk = 1;
824
825
819826         /* compress the current hunk */
820         err = chd_compress_hunk(chd, cache, &ratio);
827
828         err = chd_compress_hunk(chd, cache, &ratio, is_half_hunk);
821829         if (err != CHDERR_NONE)
822830         {
823831            fprintf(stderr, "Error during compression: %s\n", chd_error_string(err));
r14134r14135
34023410      { "-createuncomphd",   do_createhd_uncomp, 0 },
34033411      { "-createraw",      do_createraw, 0 },
34043412      { "-createcd",      do_createcd, 0 },
3413      { "-createcdflac",   do_createcd, 1 },
34053414      { "-createblankhd",   do_createblankhd, 0 },
34063415      { "-createav",      do_createav, 0 },
34073416      { "-copydata",      do_copydata, 0 },
src/osd/sdl/sdlsocket.c
r14134r14135
2323#endif
2424#include <errno.h>
2525
26#define NO_MEM_TRACKING
2627#include "emu.h"
2728#include "sdlfile.h"
2829
src/emu/video/polynew.h
r14134r14135
7070//  TYPE DEFINITIONS
7171//**************************************************************************
7272
73//-------------------------------------------------
74//  global helpers for float base types
75//-------------------------------------------------
76
77inline float poly_floor(float x) { return floorf(x); }
78inline float poly_abs(float x) { return fabsf(x); }
79inline float poly_recip(float x) { return 1.0f / x; }
80
81
82//-------------------------------------------------
83//  global helpers for double base types
84//-------------------------------------------------
85
86inline double poly_floor(double x) { return floor(x); }
87inline double poly_abs(double x) { return fabs(x); }
88inline double poly_recip(double x) { return 1.0 / x; }
89
90
7391// poly_manager is a template class
7492template<typename _BaseType, class _ObjectData, int _MaxParams, int _MaxPolys>
7593class poly_manager
r14134r14135
254272
255273
256274//-------------------------------------------------
257//  global helpers for float base types
258//-------------------------------------------------
259
260inline float poly_floor(float x) { return floorf(x); }
261inline float poly_abs(float x) { return fabsf(x); }
262inline float poly_recip(float x) { return 1.0f / x; }
263
264
265//-------------------------------------------------
266//  global helpers for double base types
267//-------------------------------------------------
268
269inline double poly_floor(double x) { return floor(x); }
270inline double poly_abs(double x) { return fabs(x); }
271inline double poly_recip(double x) { return 1.0 / x; }
272
273
274//-------------------------------------------------
275275//  poly_manager - constructor
276276//-------------------------------------------------
277277
src/emu/video.c
r14134r14135
540540   machine().render().target_free(m_snap_target);
541541   m_snap_bitmap.reset();
542542
543   // print a final result if we have at least 5 seconds' worth of data
544   if (m_overall_emutime.seconds >= 5)
543   // print a final result if we have at least 2 seconds' worth of data
544   if (m_overall_emutime.seconds >= 1)
545545   {
546546      osd_ticks_t tps = osd_ticks_per_second();
547547      double final_real_time = (double)m_overall_real_seconds + (double)m_overall_real_ticks / (double)tps;
src/emu/sound/samples.c
r14134r14135
11#include "emu.h"
22#include "emuopts.h"
33#include "samples.h"
4#include "../../lib/libflac/include/flac/all.h"
45
5
66typedef struct _sample_channel sample_channel;
77struct _sample_channel
88{
r14134r14135
4343#define FRAC_MASK      (FRAC_ONE - 1)
4444#define MAX_CHANNELS    100
4545
46struct flac_reader
47{
48   UINT8* rawdata;
49   INT16* write_data;
50   int position;
51   int length;
52   int decoded_size;
53   int sample_rate;
54   int channels;
55   int bits_per_sample;
56   int total_samples;
57   int write_position;
58} flacread;
4659
60static flac_reader* flacreadptr;
61
62void my_error_callback(const FLAC__StreamDecoder * decoder, FLAC__StreamDecoderErrorStatus status, void * client_data)
63{
64   fatalerror("FLAC error Callback\n");
65}
66
67void my_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
68{
69
70   flac_reader* flacrd =  ((flac_reader*)client_data);
71   //printf("Metadata callback\n");
72   //printf("metadata->type == %d\n", metadata->type);
73
74   if (metadata->type==0)
75   {
76      const FLAC__StreamMetadata_StreamInfo *streaminfo = &(metadata->data.stream_info);
77
78      //printf("streaminfo channels %d, sample_rate %d total %d\n", streaminfo->channels, streaminfo->sample_rate, streaminfo->total_samples);
79
80      flacrd->sample_rate = streaminfo->sample_rate;
81      flacrd->channels = streaminfo->channels;
82      flacrd->bits_per_sample = streaminfo->bits_per_sample;
83      flacrd->total_samples = streaminfo->total_samples;
84   }
85}
86
87
88
89
90FLAC__StreamDecoderReadStatus my_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
91{
92   flac_reader* flacrd =  ((flac_reader*)client_data);
93
94   //printf("read in length %d\n", flacrd->length);
95   if(*bytes > 0)
96   {
97      if (*bytes <=  flacrd->length)
98      {
99         memcpy(buffer, flacrd->rawdata+flacrd->position, *bytes);
100         flacrd->position+=*bytes;
101         flacrd->length-=*bytes;
102         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
103      }
104      else
105      {
106         memcpy(buffer, flacrd->rawdata+flacrd->position,  flacrd->length);
107          flacrd->position+= flacrd->length;
108         flacrd->length = 0;
109
110         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
111      }
112   }
113   else
114   {
115      return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
116   }
117
118   if ( flacrd->length==0)
119   {
120      return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
121   }
122
123   return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
124
125}
126
127FLAC__StreamDecoderWriteStatus my_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data)
128{
129   //printf("my_write_callback\n");
130   //printf("array size %d\n",frame->header.blocksize);
131
132   flac_reader* flacrd =  ((flac_reader*)client_data);
133
134   flacrd->decoded_size += frame->header.blocksize;
135   //printf("total array size %d\n",flacrd->decoded_size);
136
137   for (int i=0;i<frame->header.blocksize;i++)
138   {
139      flacrd->write_data[i+flacrd->write_position] = buffer[0][i];
140   }
141
142   flacrd->write_position +=  frame->header.blocksize;
143   
144   return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
145}
146
147
148
149
150
151
47152/*-------------------------------------------------
48153    read_wav_sample - read a WAV file as a sample
49154-------------------------------------------------*/
r14134r14135
55160   UINT16 bits, temp16;
56161   char buf[32];
57162   UINT32 sindex;
163   int type = 0;
58164
59165   /* read the core header and make sure it's a WAVE file */
60166   offset += file.read(buf, 4);
61167   if (offset < 4)
62168      return 0;
63   if (memcmp(&buf[0], "RIFF", 4) != 0)
169   if (memcmp(&buf[0], "RIFF", 4) == 0)
170      type = 1;
171   else if (memcmp(&buf[0], "fLaC", 4) == 0)
172      type = 2;
173   else
64174      return 0;
65175
66   /* get the total size */
67   offset += file.read(&filesize, 4);
68   if (offset < 8)
69      return 0;
70   filesize = LITTLE_ENDIANIZE_INT32(filesize);
176   if (type==1)
177   {
178      /* get the total size */
179      offset += file.read(&filesize, 4);
180      if (offset < 8)
181         return 0;
182      filesize = LITTLE_ENDIANIZE_INT32(filesize);
71183
72   /* read the RIFF file type and make sure it's a WAVE file */
73   offset += file.read(buf, 4);
74   if (offset < 12)
75      return 0;
76   if (memcmp(&buf[0], "WAVE", 4) != 0)
77      return 0;
78
79   /* seek until we find a format tag */
80   while (1)
81   {
184      /* read the RIFF file type and make sure it's a WAVE file */
82185      offset += file.read(buf, 4);
83      offset += file.read(&length, 4);
84      length = LITTLE_ENDIANIZE_INT32(length);
85      if (memcmp(&buf[0], "fmt ", 4) == 0)
86         break;
186      if (offset < 12)
187         return 0;
188      if (memcmp(&buf[0], "WAVE", 4) != 0)
189         return 0;
87190
88      /* seek to the next block */
89      file.seek(length, SEEK_CUR);
90      offset += length;
91      if (offset >= filesize)
191      /* seek until we find a format tag */
192      while (1)
193      {
194         offset += file.read(buf, 4);
195         offset += file.read(&length, 4);
196         length = LITTLE_ENDIANIZE_INT32(length);
197         if (memcmp(&buf[0], "fmt ", 4) == 0)
198            break;
199
200         /* seek to the next block */
201         file.seek(length, SEEK_CUR);
202         offset += length;
203         if (offset >= filesize)
204            return 0;
205      }
206
207      /* read the format -- make sure it is PCM */
208      offset += file.read(&temp16, 2);
209      temp16 = LITTLE_ENDIANIZE_INT16(temp16);
210      if (temp16 != 1)
92211         return 0;
93   }
94212
95   /* read the format -- make sure it is PCM */
96   offset += file.read(&temp16, 2);
97   temp16 = LITTLE_ENDIANIZE_INT16(temp16);
98   if (temp16 != 1)
99      return 0;
213      /* number of channels -- only mono is supported */
214      offset += file.read(&temp16, 2);
215      temp16 = LITTLE_ENDIANIZE_INT16(temp16);
216      if (temp16 != 1)
217         return 0;
100218
101   /* number of channels -- only mono is supported */
102   offset += file.read(&temp16, 2);
103   temp16 = LITTLE_ENDIANIZE_INT16(temp16);
104   if (temp16 != 1)
105      return 0;
219      /* sample rate */
220      offset += file.read(&rate, 4);
221      rate = LITTLE_ENDIANIZE_INT32(rate);
106222
107   /* sample rate */
108   offset += file.read(&rate, 4);
109   rate = LITTLE_ENDIANIZE_INT32(rate);
223      /* bytes/second and block alignment are ignored */
224      offset += file.read(buf, 6);
110225
111   /* bytes/second and block alignment are ignored */
112   offset += file.read(buf, 6);
226      /* bits/sample */
227      offset += file.read(&bits, 2);
228      bits = LITTLE_ENDIANIZE_INT16(bits);
229      if (bits != 8 && bits != 16)
230         return 0;
113231
114   /* bits/sample */
115   offset += file.read(&bits, 2);
116   bits = LITTLE_ENDIANIZE_INT16(bits);
117   if (bits != 8 && bits != 16)
118      return 0;
232      /* seek past any extra data */
233      file.seek(length - 16, SEEK_CUR);
234      offset += length - 16;
119235
120   /* seek past any extra data */
121   file.seek(length - 16, SEEK_CUR);
122   offset += length - 16;
236      /* seek until we find a data tag */
237      while (1)
238      {
239         offset += file.read(buf, 4);
240         offset += file.read(&length, 4);
241         length = LITTLE_ENDIANIZE_INT32(length);
242         if (memcmp(&buf[0], "data", 4) == 0)
243            break;
123244
124   /* seek until we find a data tag */
125   while (1)
126   {
127      offset += file.read(buf, 4);
128      offset += file.read(&length, 4);
129      length = LITTLE_ENDIANIZE_INT32(length);
130      if (memcmp(&buf[0], "data", 4) == 0)
131         break;
245         /* seek to the next block */
246         file.seek(length, SEEK_CUR);
247         offset += length;
248         if (offset >= filesize)
249            return 0;
250      }
132251
133      /* seek to the next block */
134      file.seek(length, SEEK_CUR);
135      offset += length;
136      if (offset >= filesize)
252      /* if there was a 0 length data block, we're done */
253      if (length == 0)
137254         return 0;
138   }
139255
140   /* if there was a 0 length data block, we're done */
141   if (length == 0)
142      return 0;
256      /* fill in the sample data */
257      sample->length = length;
258      sample->frequency = rate;
143259
144   /* fill in the sample data */
145   sample->length = length;
146   sample->frequency = rate;
260      /* read the data in */
261      if (bits == 8)
262      {
263         unsigned char *tempptr;
264         int sindex;
147265
148   /* read the data in */
149   if (bits == 8)
150   {
151      unsigned char *tempptr;
152      int sindex;
266         sample->data = auto_alloc_array(machine, INT16, length);
267         file.read(sample->data, length);
153268
154      sample->data = auto_alloc_array(machine, INT16, length);
155      file.read(sample->data, length);
269         /* convert 8-bit data to signed samples */
270         tempptr = (unsigned char *)sample->data;
271         for (sindex = length - 1; sindex >= 0; sindex--)
272            sample->data[sindex] = (INT8)(tempptr[sindex] ^ 0x80) * 256;
156273
157      /* convert 8-bit data to signed samples */
158      tempptr = (unsigned char *)sample->data;
159      for (sindex = length - 1; sindex >= 0; sindex--)
160         sample->data[sindex] = (INT8)(tempptr[sindex] ^ 0x80) * 256;
274      }
275      else
276      {
277         /* 16-bit data is fine as-is */
278         sample->data = auto_alloc_array(machine, INT16, length/2);
279         file.read(sample->data, length);
280
281            sample->length /= 2;
282         if (ENDIANNESS_NATIVE != ENDIANNESS_LITTLE)
283            for (sindex = 0; sindex < sample->length; sindex++)
284               sample->data[sindex] = LITTLE_ENDIANIZE_INT16(sample->data[sindex]);
285      }
161286   }
162287   else
163288   {
164      /* 16-bit data is fine as-is */
165      sample->data = auto_alloc_array(machine, INT16, length/2);
166      file.read(sample->data, length);
167      sample->length /= 2;
168      if (ENDIANNESS_NATIVE != ENDIANNESS_LITTLE)
169         for (sindex = 0; sindex < sample->length; sindex++)
170            sample->data[sindex] = LITTLE_ENDIANIZE_INT16(sample->data[sindex]);
289      int length;
290
291      file.seek(0, SEEK_END);
292      length = file.tell();
293      file.seek(0, 0);
294
295      flacread.rawdata = auto_alloc_array(machine, UINT8, length);
296      flacread.length = length;
297      flacread.position = 0;
298      flacread.decoded_size = 0;
299
300      flacreadptr = &flacread;
301
302      file.read(flacread.rawdata, length);
303
304      FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
305
306      if (!decoder)
307         fatalerror("Fail FLAC__stream_decoder_new\n");
308
309      if(FLAC__stream_decoder_init_stream(
310         decoder,
311         my_read_callback,
312         NULL, //my_seek_callback,      // or NULL
313         NULL, //my_tell_callback,      // or NULL
314         NULL, //my_length_callback,    // or NULL
315         NULL, //my_eof_callback,       // or NULL
316         my_write_callback,
317         my_metadata_callback, //my_metadata_callback,  // or NULL
318         my_error_callback,
319         (void*)flacreadptr /*my_client_data*/ ) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
320         fatalerror("Fail FLAC__stream_decoder_init_stream\n");
321
322      if (FLAC__stream_decoder_process_until_end_of_metadata(decoder) != FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM)
323         fatalerror("Fail FLAC__stream_decoder_process_until_end_of_metadata\n");
324
325      //printf("got metadata?\n");
326
327      if (flacread.channels != 1) // only Mono supported
328         return 0;
329
330      int size = flacread.total_samples * (flacread.bits_per_sample/8);
331   
332      sample->data = auto_alloc_array(machine, INT16, size);
333      flacread.write_position = 0;
334      flacread.write_data = sample->data;
335
336      if (FLAC__stream_decoder_process_until_end_of_stream (decoder) != FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM)
337         fatalerror("Fail FLAC__stream_decoder_process_until_end_of_stream\n");
338
339      if (FLAC__stream_decoder_finish (decoder) != true)
340         fatalerror("Fail FLAC__stream_decoder_finish\n");
341
342      FLAC__stream_decoder_delete(decoder);
343
344      /* fill in the sample data */
345     
346      sample->frequency = flacread.sample_rate;
347      sample->length = size;
348
349      if (flacread.bits_per_sample == 8)
350      {
351         for (sindex = 0; sindex <= sample->length; sindex++)
352            sample->data[sindex] = ((sample->data[sindex])&0xff)*256;
353      }
354      else // don't need to process 16-bit samples?
355      {
356         sample->length = sample->length /2; //??
357      }
171358   }
359
172360   return 1;
173361}
174362
src/emu/drivers/xtal.h
r14134r14135
176176   XTAL_36MHz        = 36000000,      /* Sega Model 1 video board */
177177   XTAL_38_76922MHz   = 38769220,      /* Namco System 21 video board */
178178   XTAL_40MHz        = 40000000,
179        XTAL_42MHz        = 42000000,      /* BMC A-00211 - Popo Bear */
179180   XTAL_42_9545MHz    = 42954545,      /* CPS3 */
180181   XTAL_44_1MHz      = 44100000,      /* Subsino's Bishou Jan */
181182   XTAL_45MHz        = 45000000,      /* Eolith with Hyperstone CPUs */
src/lib/libflac/libflac++/metadata.cpp
r0r14135
1/* libFLAC++ - Free Lossless Audio Codec library
2 * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31 
32#define __STDC_LIMIT_MACROS 1 /* otherwise SIZE_MAX is not defined for c++ */
33#include "share/alloc.h"
34#include "flac++/metadata.h"
35#include "flac/assert.h"
36#include <stdlib.h> // for malloc(), free()
37#include <string.h> // for memcpy() etc.
38 
39#ifdef _MSC_VER
40// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning)
41#pragma warning ( disable : 4800 )
42#endif
43 
44namespace FLAC {
45   namespace Metadata {
46 
47      // local utility routines
48 
49      namespace local {
50 
51         Prototype *construct_block(::FLAC__StreamMetadata *object)
52         {
53            Prototype *ret = 0;
54            switch(object->type) {
55               case FLAC__METADATA_TYPE_STREAMINFO:
56                  ret = new StreamInfo(object, /*copy=*/false);
57                  break;
58               case FLAC__METADATA_TYPE_PADDING:
59                  ret = new Padding(object, /*copy=*/false);
60                  break;
61               case FLAC__METADATA_TYPE_APPLICATION:
62                  ret = new Application(object, /*copy=*/false);
63                  break;
64               case FLAC__METADATA_TYPE_SEEKTABLE:
65                  ret = new SeekTable(object, /*copy=*/false);
66                  break;
67               case FLAC__METADATA_TYPE_VORBIS_COMMENT:
68                  ret = new VorbisComment(object, /*copy=*/false);
69                  break;
70               case FLAC__METADATA_TYPE_CUESHEET:
71                  ret = new CueSheet(object, /*copy=*/false);
72                  break;
73               case FLAC__METADATA_TYPE_PICTURE:
74                  ret = new Picture(object, /*copy=*/false);
75                  break;
76               default:
77                  ret = new Unknown(object, /*copy=*/false);
78                  break;
79            }
80            return ret;
81         }
82 
83      }
84 
85      FLACPP_API Prototype *clone(const Prototype *object)
86      {
87         FLAC__ASSERT(0 != object);
88 
89         const StreamInfo *streaminfo = dynamic_cast<const StreamInfo *>(object);
90         const Padding *padding = dynamic_cast<const Padding *>(object);
91         const Application *application = dynamic_cast<const Application *>(object);
92         const SeekTable *seektable = dynamic_cast<const SeekTable *>(object);
93         const VorbisComment *vorbiscomment = dynamic_cast<const VorbisComment *>(object);
94         const CueSheet *cuesheet = dynamic_cast<const CueSheet *>(object);
95         const Picture *picture = dynamic_cast<const Picture *>(object);
96         const Unknown *unknown = dynamic_cast<const Unknown *>(object);
97 
98         if(0 != streaminfo)
99            return new StreamInfo(*streaminfo);
100         else if(0 != padding)
101            return new Padding(*padding);
102         else if(0 != application)
103            return new Application(*application);
104         else if(0 != seektable)
105            return new SeekTable(*seektable);
106         else if(0 != vorbiscomment)
107            return new VorbisComment(*vorbiscomment);
108         else if(0 != cuesheet)
109            return new CueSheet(*cuesheet);
110         else if(0 != picture)
111            return new Picture(*picture);
112         else if(0 != unknown)
113            return new Unknown(*unknown);
114         else {
115            FLAC__ASSERT(0);
116            return 0;
117         }
118      }
119 
120      //
121      // Prototype
122      //
123 
124      Prototype::Prototype(const Prototype &object):
125      object_(::FLAC__metadata_object_clone(object.object_)),
126      is_reference_(false)
127      {
128         FLAC__ASSERT(object.is_valid());
129      }
130 
131      Prototype::Prototype(const ::FLAC__StreamMetadata &object):
132      object_(::FLAC__metadata_object_clone(&object)),
133      is_reference_(false)
134      {
135      }
136 
137      Prototype::Prototype(const ::FLAC__StreamMetadata *object):
138      object_(::FLAC__metadata_object_clone(object)),
139      is_reference_(false)
140      {
141         FLAC__ASSERT(0 != object);
142      }
143 
144      Prototype::Prototype(::FLAC__StreamMetadata *object, bool copy):
145      object_(copy? ::FLAC__metadata_object_clone(object) : object),
146      is_reference_(false)
147      {
148         FLAC__ASSERT(0 != object);
149      }
150 
151      Prototype::~Prototype()
152      {
153         clear();
154      }
155 
156      void Prototype::clear()
157      {
158         if(0 != object_ && !is_reference_)
159            FLAC__metadata_object_delete(object_);
160         object_ = 0;
161      }
162 
163      Prototype &Prototype::operator=(const Prototype &object)
164      {
165         FLAC__ASSERT(object.is_valid());
166         clear();
167         is_reference_ = false;
168         object_ = ::FLAC__metadata_object_clone(object.object_);
169         return *this;
170      }
171 
172      Prototype &Prototype::operator=(const ::FLAC__StreamMetadata &object)
173      {
174         clear();
175         is_reference_ = false;
176         object_ = ::FLAC__metadata_object_clone(&object);
177         return *this;
178      }
179 
180      Prototype &Prototype::operator=(const ::FLAC__StreamMetadata *object)
181      {
182         FLAC__ASSERT(0 != object);
183         clear();
184         is_reference_ = false;
185         object_ = ::FLAC__metadata_object_clone(object);
186         return *this;
187      }
188 
189      Prototype &Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy)
190      {
191         FLAC__ASSERT(0 != object);
192         clear();
193         object_ = (copy? ::FLAC__metadata_object_clone(object) : object);
194         is_reference_ = false;
195         return *this;
196      }
197 
198      bool Prototype::get_is_last() const
199      {
200         FLAC__ASSERT(is_valid());
201         return (bool)object_->is_last;
202      }
203 
204      FLAC__MetadataType Prototype::get_type() const
205      {
206         FLAC__ASSERT(is_valid());
207         return object_->type;
208      }
209 
210      unsigned Prototype::get_length() const
211      {
212         FLAC__ASSERT(is_valid());
213         return object_->length;
214      }
215 
216      void Prototype::set_is_last(bool value)
217      {
218         FLAC__ASSERT(is_valid());
219         object_->is_last = value;
220      }
221 
222 
223      //
224      // StreamInfo
225      //
226 
227      StreamInfo::StreamInfo():
228      Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_STREAMINFO), /*copy=*/false)
229      { }
230 
231      StreamInfo::~StreamInfo()
232      { }
233 
234      unsigned StreamInfo::get_min_blocksize() const
235      {
236         FLAC__ASSERT(is_valid());
237         return object_->data.stream_info.min_blocksize;
238      }
239 
240      unsigned StreamInfo::get_max_blocksize() const
241      {
242         FLAC__ASSERT(is_valid());
243         return object_->data.stream_info.max_blocksize;
244      }
245 
246      unsigned StreamInfo::get_min_framesize() const
247      {
248         FLAC__ASSERT(is_valid());
249         return object_->data.stream_info.min_framesize;
250      }
251 
252      unsigned StreamInfo::get_max_framesize() const
253      {
254         FLAC__ASSERT(is_valid());
255         return object_->data.stream_info.max_framesize;
256      }
257 
258      unsigned StreamInfo::get_sample_rate() const
259      {
260         FLAC__ASSERT(is_valid());
261         return object_->data.stream_info.sample_rate;
262      }
263 
264      unsigned StreamInfo::get_channels() const
265      {
266         FLAC__ASSERT(is_valid());
267         return object_->data.stream_info.channels;
268      }
269 
270      unsigned StreamInfo::get_bits_per_sample() const
271      {
272         FLAC__ASSERT(is_valid());
273         return object_->data.stream_info.bits_per_sample;
274      }
275 
276      FLAC__uint64 StreamInfo::get_total_samples() const
277      {
278         FLAC__ASSERT(is_valid());
279         return object_->data.stream_info.total_samples;
280      }
281 
282      const FLAC__byte *StreamInfo::get_md5sum() const
283      {
284         FLAC__ASSERT(is_valid());
285         return object_->data.stream_info.md5sum;
286      }
287 
288      void StreamInfo::set_min_blocksize(unsigned value)
289      {
290         FLAC__ASSERT(is_valid());
291         FLAC__ASSERT(value >= FLAC__MIN_BLOCK_SIZE);
292         FLAC__ASSERT(value <= FLAC__MAX_BLOCK_SIZE);
293         object_->data.stream_info.min_blocksize = value;
294      }
295 
296      void StreamInfo::set_max_blocksize(unsigned value)
297      {
298         FLAC__ASSERT(is_valid());
299         FLAC__ASSERT(value >= FLAC__MIN_BLOCK_SIZE);
300         FLAC__ASSERT(value <= FLAC__MAX_BLOCK_SIZE);
301         object_->data.stream_info.max_blocksize = value;
302      }
303 
304      void StreamInfo::set_min_framesize(unsigned value)
305      {
306         FLAC__ASSERT(is_valid());
307         FLAC__ASSERT(value < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
308         object_->data.stream_info.min_framesize = value;
309      }
310 
311      void StreamInfo::set_max_framesize(unsigned value)
312      {
313         FLAC__ASSERT(is_valid());
314         FLAC__ASSERT(value < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
315         object_->data.stream_info.max_framesize = value;
316      }
317 
318      void StreamInfo::set_sample_rate(unsigned value)
319      {
320         FLAC__ASSERT(is_valid());
321         FLAC__ASSERT(FLAC__format_sample_rate_is_valid(value));
322         object_->data.stream_info.sample_rate = value;
323      }
324 
325      void StreamInfo::set_channels(unsigned value)
326      {
327         FLAC__ASSERT(is_valid());
328         FLAC__ASSERT(value > 0);
329         FLAC__ASSERT(value <= FLAC__MAX_CHANNELS);
330         object_->data.stream_info.channels = value;
331      }
332 
333      void StreamInfo::set_bits_per_sample(unsigned value)
334      {
335         FLAC__ASSERT(is_valid());
336         FLAC__ASSERT(value >= FLAC__MIN_BITS_PER_SAMPLE);
337         FLAC__ASSERT(value <= FLAC__MAX_BITS_PER_SAMPLE);
338         object_->data.stream_info.bits_per_sample = value;
339      }
340 
341      void StreamInfo::set_total_samples(FLAC__uint64 value)
342      {
343         FLAC__ASSERT(is_valid());
344         FLAC__ASSERT(value < (((FLAC__uint64)1) << FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN));
345         object_->data.stream_info.total_samples = value;
346      }
347 
348      void StreamInfo::set_md5sum(const FLAC__byte value[16])
349      {
350         FLAC__ASSERT(is_valid());
351         FLAC__ASSERT(0 != value);
352         memcpy(object_->data.stream_info.md5sum, value, 16);
353      }
354 
355 
356      //
357      // Padding
358      //
359 
360      Padding::Padding():
361      Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING), /*copy=*/false)
362      { }
363 
364      Padding::~Padding()
365      { }
366 
367      void Padding::set_length(unsigned length)
368      {
369         FLAC__ASSERT(is_valid());
370         object_->length = length;
371      }
372 
373 
374      //
375      // Application
376      //
377 
378      Application::Application():
379      Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_APPLICATION), /*copy=*/false)
380      { }
381 
382      Application::~Application()
383      { }
384 
385      const FLAC__byte *Application::get_id() const
386      {
387         FLAC__ASSERT(is_valid());
388         return object_->data.application.id;
389      }
390 
391      const FLAC__byte *Application::get_data() const
392      {
393         FLAC__ASSERT(is_valid());
394         return object_->data.application.data;
395      }
396 
397      void Application::set_id(const FLAC__byte value[4])
398      {
399         FLAC__ASSERT(is_valid());
400         FLAC__ASSERT(0 != value);
401         memcpy(object_->data.application.id, value, 4);
402      }
403 
404      bool Application::set_data(const FLAC__byte *data, unsigned length)
405      {
406         FLAC__ASSERT(is_valid());
407         return (bool)::FLAC__metadata_object_application_set_data(object_, (FLAC__byte*)data, length, true);
408      }
409 
410      bool Application::set_data(FLAC__byte *data, unsigned length, bool copy)
411      {
412         FLAC__ASSERT(is_valid());
413         return (bool)::FLAC__metadata_object_application_set_data(object_, data, length, copy);
414      }
415 
416 
417      //
418      // SeekTable
419      //
420 
421      SeekTable::SeekTable():
422      Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE), /*copy=*/false)
423      { }
424 
425      SeekTable::~SeekTable()
426      { }
427 
428      unsigned SeekTable::get_num_points() const
429      {
430         FLAC__ASSERT(is_valid());
431         return object_->data.seek_table.num_points;
432      }
433 
434      ::FLAC__StreamMetadata_SeekPoint SeekTable::get_point(unsigned index) const
435      {
436         FLAC__ASSERT(is_valid());
437         FLAC__ASSERT(index < object_->data.seek_table.num_points);
438         return object_->data.seek_table.points[index];
439      }
440 
441      void SeekTable::set_point(unsigned index, const ::FLAC__StreamMetadata_SeekPoint &point)
442      {
443         FLAC__ASSERT(is_valid());
444         FLAC__ASSERT(index < object_->data.seek_table.num_points);
445         ::FLAC__metadata_object_seektable_set_point(object_, index, point);
446      }
447 
448      bool SeekTable::insert_point(unsigned index, const ::FLAC__StreamMetadata_SeekPoint &point)
449      {
450         FLAC__ASSERT(is_valid());
451         FLAC__ASSERT(index <= object_->data.seek_table.num_points);
452         return (bool)::FLAC__metadata_object_seektable_insert_point(object_, index, point);
453      }
454 
455      bool SeekTable::delete_point(unsigned index)
456      {
457         FLAC__ASSERT(is_valid());
458         FLAC__ASSERT(index < object_->data.seek_table.num_points);
459         return (bool)::FLAC__metadata_object_seektable_delete_point(object_, index);
460      }
461 
462      bool SeekTable::is_legal() const
463      {
464         FLAC__ASSERT(is_valid());
465         return (bool)::FLAC__metadata_object_seektable_is_legal(object_);
466      }
467 
468 
469      //
470      // VorbisComment::Entry
471      //
472 
473      VorbisComment::Entry::Entry()
474      {
475         zero();
476      }
477 
478      VorbisComment::Entry::Entry(const char *field, unsigned field_length)
479      {
480         zero();
481         construct(field, field_length);
482      }
483 
484      VorbisComment::Entry::Entry(const char *field)
485      {
486         zero();
487         construct(field);
488      }
489 
490      VorbisComment::Entry::Entry(const char *field_name, const char *field_value, unsigned field_value_length)
491      {
492         zero();
493         construct(field_name, field_value, field_value_length);
494      }
495 
496      VorbisComment::Entry::Entry(const char *field_name, const char *field_value)
497      {
498         zero();
499         construct(field_name, field_value);
500      }
501 
502      VorbisComment::Entry::Entry(const Entry &entry)
503      {
504         FLAC__ASSERT(entry.is_valid());
505         zero();
506         construct((const char *)entry.entry_.entry, entry.entry_.length);
507      }
508 
509      VorbisComment::Entry &VorbisComment::Entry::operator=(const Entry &entry)
510      {
511         FLAC__ASSERT(entry.is_valid());
512         clear();
513         construct((const char *)entry.entry_.entry, entry.entry_.length);
514         return *this;
515      }
516 
517      VorbisComment::Entry::~Entry()
518      {
519         clear();
520      }
521 
522      bool VorbisComment::Entry::is_valid() const
523      {
524         return is_valid_;
525      }
526 
527      unsigned VorbisComment::Entry::get_field_length() const
528      {
529         FLAC__ASSERT(is_valid());
530         return entry_.length;
531      }
532 
533      unsigned VorbisComment::Entry::get_field_name_length() const
534      {
535         FLAC__ASSERT(is_valid());
536         return field_name_length_;
537      }
538 
539      unsigned VorbisComment::Entry::get_field_value_length() const
540      {
541         FLAC__ASSERT(is_valid());
542         return field_value_length_;
543      }
544 
545      ::FLAC__StreamMetadata_VorbisComment_Entry VorbisComment::Entry::get_entry() const
546      {
547         FLAC__ASSERT(is_valid());
548         return entry_;
549      }
550 
551      const char *VorbisComment::Entry::get_field() const
552      {
553         FLAC__ASSERT(is_valid());
554         return (const char *)entry_.entry;
555      }
556 
557      const char *VorbisComment::Entry::get_field_name() const
558      {
559         FLAC__ASSERT(is_valid());
560         return field_name_;
561      }
562 
563      const char *VorbisComment::Entry::get_field_value() const
564      {
565         FLAC__ASSERT(is_valid());
566         return field_value_;
567      }
568 
569      bool VorbisComment::Entry::set_field(const char *field, unsigned field_length)
570      {
571         FLAC__ASSERT(is_valid());
572         FLAC__ASSERT(0 != field);
573 
574         if(!::FLAC__format_vorbiscomment_entry_is_legal((const ::FLAC__byte*)field, field_length))
575            return is_valid_ = false;
576 
577         clear_entry();
578 
579         if(0 == (entry_.entry = (FLAC__byte*)safe_malloc_add_2op_(field_length, /*+*/1))) {
580            is_valid_ = false;
581         }
582         else {
583            entry_.length = field_length;
584            memcpy(entry_.entry, field, field_length);
585            entry_.entry[field_length] = '\0';
586            (void) parse_field();
587         }
588 
589         return is_valid_;
590      }
591 
592      bool VorbisComment::Entry::set_field(const char *field)
593      {
594         return set_field(field, strlen(field));
595      }
596 
597      bool VorbisComment::Entry::set_field_name(const char *field_name)
598      {
599         FLAC__ASSERT(is_valid());
600         FLAC__ASSERT(0 != field_name);
601 
602         if(!::FLAC__format_vorbiscomment_entry_name_is_legal(field_name))
603            return is_valid_ = false;
604 
605         clear_field_name();
606 
607         if(0 == (field_name_ = strdup(field_name))) {
608            is_valid_ = false;
609         }
610         else {
611            field_name_length_ = strlen(field_name_);
612            compose_field();
613         }
614 
615         return is_valid_;
616      }
617 
618      bool VorbisComment::Entry::set_field_value(const char *field_value, unsigned field_value_length)
619      {
620         FLAC__ASSERT(is_valid());
621         FLAC__ASSERT(0 != field_value);
622 
623         if(!::FLAC__format_vorbiscomment_entry_value_is_legal((const FLAC__byte*)field_value, field_value_length))
624            return is_valid_ = false;
625 
626         clear_field_value();
627 
628         if(0 == (field_value_ = (char *)safe_malloc_add_2op_(field_value_length, /*+*/1))) {
629            is_valid_ = false;
630         }
631         else {
632            field_value_length_ = field_value_length;
633            memcpy(field_value_, field_value, field_value_length);
634            field_value_[field_value_length] = '\0';
635            compose_field();
636         }
637 
638         return is_valid_;
639      }
640 
641      bool VorbisComment::Entry::set_field_value(const char *field_value)
642      {
643         return set_field_value(field_value, strlen(field_value));
644      }
645 
646      void VorbisComment::Entry::zero()
647      {
648         is_valid_ = true;
649         entry_.length = 0;
650         entry_.entry = 0;
651         field_name_ = 0;
652         field_name_length_ = 0;
653         field_value_ = 0;
654         field_value_length_ = 0;
655      }
656 
657      void VorbisComment::Entry::clear()
658      {
659         clear_entry();
660         clear_field_name();
661         clear_field_value();
662         is_valid_ = true;
663      }
664 
665      void VorbisComment::Entry::clear_entry()
666      {
667         if(0 != entry_.entry) {
668            free(entry_.entry);
669            entry_.entry = 0;
670            entry_.length = 0;
671         }
672      }
673 
674      void VorbisComment::Entry::clear_field_name()
675      {
676         if(0 != field_name_) {
677            free(field_name_);
678            field_name_ = 0;
679            field_name_length_ = 0;
680         }
681      }
682 
683      void VorbisComment::Entry::clear_field_value()
684      {
685         if(0 != field_value_) {
686            free(field_value_);
687            field_value_ = 0;
688            field_value_length_ = 0;
689         }
690      }
691 
692      void VorbisComment::Entry::construct(const char *field, unsigned field_length)
693      {
694         if(set_field(field, field_length))
695            parse_field();
696      }
697 
698      void VorbisComment::Entry::construct(const char *field)
699      {
700         construct(field, strlen(field));
701      }
702 
703      void VorbisComment::Entry::construct(const char *field_name, const char *field_value, unsigned field_value_length)
704      {
705         if(set_field_name(field_name) && set_field_value(field_value, field_value_length))
706            compose_field();
707      }
708 
709      void VorbisComment::Entry::construct(const char *field_name, const char *field_value)
710      {
711         construct(field_name, field_value, strlen(field_value));
712      }
713 
714      void VorbisComment::Entry::compose_field()
715      {
716         clear_entry();
717 
718         if(0 == (entry_.entry = (FLAC__byte*)safe_malloc_add_4op_(field_name_length_, /*+*/1, /*+*/field_value_length_, /*+*/1))) {
719            is_valid_ = false;
720         }
721         else {
722            memcpy(entry_.entry, field_name_, field_name_length_);
723            entry_.length += field_name_length_;
724            memcpy(entry_.entry + entry_.length, "=", 1);
725            entry_.length += 1;
726            memcpy(entry_.entry + entry_.length, field_value_, field_value_length_);
727            entry_.length += field_value_length_;
728            entry_.entry[entry_.length] = '\0';
729            is_valid_ = true;
730         }
731      }
732 
733      void VorbisComment::Entry::parse_field()
734      {
735         clear_field_name();
736         clear_field_value();
737 
738         const char *p = (const char *)memchr(entry_.entry, '=', entry_.length);
739 
740         if(0 == p)
741            p = (const char *)entry_.entry + entry_.length;
742 
743         field_name_length_ = (unsigned)(p - (const char *)entry_.entry);
744         if(0 == (field_name_ = (char *)safe_malloc_add_2op_(field_name_length_, /*+*/1))) { // +1 for the trailing \0
745            is_valid_ = false;
746            return;
747         }
748         memcpy(field_name_, entry_.entry, field_name_length_);
749         field_name_[field_name_length_] = '\0';
750 
751         if(entry_.length - field_name_length_ == 0) {
752            field_value_length_ = 0;
753            if(0 == (field_value_ = (char *)safe_malloc_(0))) {
754               is_valid_ = false;
755               return;
756            }
757         }
758         else {
759            field_value_length_ = entry_.length - field_name_length_ - 1;
760            if(0 == (field_value_ = (char *)safe_malloc_add_2op_(field_value_length_, /*+*/1))) { // +1 for the trailing \0
761               is_valid_ = false;
762               return;
763            }
764            memcpy(field_value_, ++p, field_value_length_);
765            field_value_[field_value_length_] = '\0';
766         }
767 
768         is_valid_ = true;
769      }
770 
771 
772      //
773      // VorbisComment
774      //
775 
776      VorbisComment::VorbisComment():
777      Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT), /*copy=*/false)
778      { }
779 
780      VorbisComment::~VorbisComment()
781      { }
782 
783      unsigned VorbisComment::get_num_comments() const
784      {
785         FLAC__ASSERT(is_valid());
786         return object_->data.vorbis_comment.num_comments;
787      }
788 
789      const FLAC__byte *VorbisComment::get_vendor_string() const
790      {
791         FLAC__ASSERT(is_valid());
792         return object_->data.vorbis_comment.vendor_string.entry;
793      }
794 
795      VorbisComment::Entry VorbisComment::get_comment(unsigned index) const
796      {
797         FLAC__ASSERT(is_valid());
798         FLAC__ASSERT(index < object_->data.vorbis_comment.num_comments);
799         return Entry((const char *)object_->data.vorbis_comment.comments[index].entry, object_->data.vorbis_comment.comments[index].length);
800      }
801 
802      bool VorbisComment::set_vendor_string(const FLAC__byte *string)
803      {
804         FLAC__ASSERT(is_valid());
805         // vendor_string is a special kind of entry
806         const ::FLAC__StreamMetadata_VorbisComment_Entry vendor_string = { strlen((const char *)string), (FLAC__byte*)string }; // we can cheat on const-ness because we make a copy below:
807         return (bool)::FLAC__metadata_object_vorbiscomment_set_vendor_string(object_, vendor_string, /*copy=*/true);
808      }
809 
810      bool VorbisComment::set_comment(unsigned index, const VorbisComment::Entry &entry)
811      {
812         FLAC__ASSERT(is_valid());
813         FLAC__ASSERT(index < object_->data.vorbis_comment.num_comments);
814         return (bool)::FLAC__metadata_object_vorbiscomment_set_comment(object_, index, entry.get_entry(), /*copy=*/true);
815      }
816 
817      bool VorbisComment::insert_comment(unsigned index, const VorbisComment::Entry &entry)
818      {
819         FLAC__ASSERT(is_valid());
820         FLAC__ASSERT(index <= object_->data.vorbis_comment.num_comments);
821         return (bool)::FLAC__metadata_object_vorbiscomment_insert_comment(object_, index, entry.get_entry(), /*copy=*/true);
822      }
823 
824      bool VorbisComment::append_comment(const VorbisComment::Entry &entry)
825      {
826         FLAC__ASSERT(is_valid());
827         return (bool)::FLAC__metadata_object_vorbiscomment_append_comment(object_, entry.get_entry(), /*copy=*/true);
828      }
829 
830      bool VorbisComment::delete_comment(unsigned index)
831      {
832         FLAC__ASSERT(is_valid());
833         FLAC__ASSERT(index < object_->data.vorbis_comment.num_comments);
834         return (bool)::FLAC__metadata_object_vorbiscomment_delete_comment(object_, index);
835      }
836 
837 
838      //
839      // CueSheet::Track
840      //
841 
842      CueSheet::Track::Track():
843      object_(::FLAC__metadata_object_cuesheet_track_new())
844      { }
845 
846      CueSheet::Track::Track(const ::FLAC__StreamMetadata_CueSheet_Track *track):
847      object_(::FLAC__metadata_object_cuesheet_track_clone(track))
848      { }
849 
850      CueSheet::Track::Track(const Track &track):
851      object_(::FLAC__metadata_object_cuesheet_track_clone(track.object_))
852      { }
853 
854      CueSheet::Track &CueSheet::Track::operator=(const Track &track)
855      {
856         if(0 != object_)
857            ::FLAC__metadata_object_cuesheet_track_delete(object_);
858         object_ = ::FLAC__metadata_object_cuesheet_track_clone(track.object_);
859         return *this;
860      }
861 
862      CueSheet::Track::~Track()
863      {
864         if(0 != object_)
865            ::FLAC__metadata_object_cuesheet_track_delete(object_);
866      }
867 
868      bool CueSheet::Track::is_valid() const
869      {
870         return(0 != object_);
871      }
872 
873      ::FLAC__StreamMetadata_CueSheet_Index CueSheet::Track::get_index(unsigned i) const
874      {
875         FLAC__ASSERT(is_valid());
876         FLAC__ASSERT(i < object_->num_indices);
877         return object_->indices[i];
878      }
879 
880      void CueSheet::Track::set_isrc(const char value[12])
881      {
882         FLAC__ASSERT(is_valid());
883         FLAC__ASSERT(0 != value);
884         memcpy(object_->isrc, value, 12);
885         object_->isrc[12] = '\0';
886      }
887 
888      void CueSheet::Track::set_type(unsigned value)
889      {
890         FLAC__ASSERT(is_valid());
891         FLAC__ASSERT(value <= 1);
892         object_->type = value;
893      }
894 
895       void CueSheet::Track::set_index(unsigned i, const ::FLAC__StreamMetadata_CueSheet_Index &index)
896       {
897          FLAC__ASSERT(is_valid());
898          FLAC__ASSERT(i < object_->num_indices);
899          object_->indices[i] = index;
900       }
901 
902 
903      //
904      // CueSheet
905      //
906 
907      CueSheet::CueSheet():
908      Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_CUESHEET), /*copy=*/false)
909      { }
910 
911      CueSheet::~CueSheet()
912      { }
913 
914      const char *CueSheet::get_media_catalog_number() const
915      {
916         FLAC__ASSERT(is_valid());
917         return object_->data.cue_sheet.media_catalog_number;
918      }
919 
920      FLAC__uint64 CueSheet::get_lead_in() const
921      {
922         FLAC__ASSERT(is_valid());
923         return object_->data.cue_sheet.lead_in;
924      }
925 
926      bool CueSheet::get_is_cd() const
927      {
928         FLAC__ASSERT(is_valid());
929         return object_->data.cue_sheet.is_cd? true : false;
930      }
931 
932      unsigned CueSheet::get_num_tracks() const
933      {
934         FLAC__ASSERT(is_valid());
935         return object_->data.cue_sheet.num_tracks;
936      }
937 
938      CueSheet::Track CueSheet::get_track(unsigned i) const
939      {
940         FLAC__ASSERT(is_valid());
941         FLAC__ASSERT(i < object_->data.cue_sheet.num_tracks);
942         return Track(object_->data.cue_sheet.tracks + i);
943      }
944 
945      void CueSheet::set_media_catalog_number(const char value[128])
946      {
947         FLAC__ASSERT(is_valid());
948         FLAC__ASSERT(0 != value);
949         memcpy(object_->data.cue_sheet.media_catalog_number, value, 128);
950         object_->data.cue_sheet.media_catalog_number[128] = '\0';
951      }
952 
953      void CueSheet::set_lead_in(FLAC__uint64 value)
954      {
955         FLAC__ASSERT(is_valid());
956         object_->data.cue_sheet.lead_in = value;
957      }
958 
959      void CueSheet::set_is_cd(bool value)
960      {
961         FLAC__ASSERT(is_valid());
962         object_->data.cue_sheet.is_cd = value;
963      }
964 
965      void CueSheet::set_index(unsigned track_num, unsigned index_num, const ::FLAC__StreamMetadata_CueSheet_Index &index)
966      {
967         FLAC__ASSERT(is_valid());
968         FLAC__ASSERT(track_num < object_->data.cue_sheet.num_tracks);
969         FLAC__ASSERT(index_num < object_->data.cue_sheet.tracks[track_num].num_indices);
970         object_->data.cue_sheet.tracks[track_num].indices[index_num] = index;
971      }
972 
973      bool CueSheet::insert_index(unsigned track_num, unsigned index_num, const ::FLAC__StreamMetadata_CueSheet_Index &index)
974      {
975         FLAC__ASSERT(is_valid());
976         FLAC__ASSERT(track_num < object_->data.cue_sheet.num_tracks);
977         FLAC__ASSERT(index_num <= object_->data.cue_sheet.tracks[track_num].num_indices);
978         return (bool)::FLAC__metadata_object_cuesheet_track_insert_index(object_, track_num, index_num, index);
979      }
980 
981      bool CueSheet::delete_index(unsigned track_num, unsigned index_num)
982      {
983         FLAC__ASSERT(is_valid());
984         FLAC__ASSERT(track_num < object_->data.cue_sheet.num_tracks);
985         FLAC__ASSERT(index_num < object_->data.cue_sheet.tracks[track_num].num_indices);
986         return (bool)::FLAC__metadata_object_cuesheet_track_delete_index(object_, track_num, index_num);
987      }
988 
989      bool CueSheet::set_track(unsigned i, const CueSheet::Track &track)
990      {
991         FLAC__ASSERT(is_valid());
992         FLAC__ASSERT(i < object_->data.cue_sheet.num_tracks);
993         // We can safely const_cast since copy=true
994         return (bool)::FLAC__metadata_object_cuesheet_set_track(object_, i, const_cast< ::FLAC__StreamMetadata_CueSheet_Track*>(track.get_track()), /*copy=*/true);
995      }
996 
997      bool CueSheet::insert_track(unsigned i, const CueSheet::Track &track)
998      {
999         FLAC__ASSERT(is_valid());
1000         FLAC__ASSERT(i <= object_->data.cue_sheet.num_tracks);
1001         // We can safely const_cast since copy=true
1002         return (bool)::FLAC__metadata_object_cuesheet_insert_track(object_, i, const_cast< ::FLAC__StreamMetadata_CueSheet_Track*>(track.get_track()), /*copy=*/true);
1003      }
1004 
1005      bool CueSheet::delete_track(unsigned i)
1006      {
1007         FLAC__ASSERT(is_valid());
1008         FLAC__ASSERT(i < object_->data.cue_sheet.num_tracks);
1009         return (bool)::FLAC__metadata_object_cuesheet_delete_track(object_, i);
1010      }
1011 
1012      bool CueSheet::is_legal(bool check_cd_da_subset, const char **violation) const
1013      {
1014         FLAC__ASSERT(is_valid());
1015         return (bool)::FLAC__metadata_object_cuesheet_is_legal(object_, check_cd_da_subset, violation);
1016      }
1017 
1018      FLAC__uint32 CueSheet::calculate_cddb_id() const
1019      {
1020         FLAC__ASSERT(is_valid());
1021         return ::FLAC__metadata_object_cuesheet_calculate_cddb_id(object_);
1022      }
1023 
1024 
1025      //
1026      // Picture
1027      //
1028 
1029      Picture::Picture():
1030      Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_PICTURE), /*copy=*/false)
1031      { }
1032 
1033      Picture::~Picture()
1034      { }
1035 
1036      ::FLAC__StreamMetadata_Picture_Type Picture::get_type() const
1037      {
1038         FLAC__ASSERT(is_valid());
1039         return object_->data.picture.type;
1040      }
1041 
1042      const char *Picture::get_mime_type() const
1043      {
1044         FLAC__ASSERT(is_valid());
1045         return object_->data.picture.mime_type;
1046      }
1047 
1048      const FLAC__byte *Picture::get_description() const
1049      {
1050         FLAC__ASSERT(is_valid());
1051         return object_->data.picture.description;
1052      }
1053 
1054      FLAC__uint32 Picture::get_width() const
1055      {
1056         FLAC__ASSERT(is_valid());
1057         return object_->data.picture.width;
1058      }
1059 
1060      FLAC__uint32 Picture::get_height() const
1061      {
1062         FLAC__ASSERT(is_valid());
1063         return object_->data.picture.height;
1064      }
1065 
1066      FLAC__uint32 Picture::get_depth() const
1067      {
1068         FLAC__ASSERT(is_valid());
1069         return object_->data.picture.depth;
1070      }
1071 
1072      FLAC__uint32 Picture::get_colors() const
1073      {
1074         FLAC__ASSERT(is_valid());
1075         return object_->data.picture.colors;
1076      }
1077 
1078      FLAC__uint32 Picture::get_data_length() const
1079      {
1080         FLAC__ASSERT(is_valid());
1081         return object_->data.picture.data_length;
1082      }
1083 
1084      const FLAC__byte *Picture::get_data() const
1085      {
1086         FLAC__ASSERT(is_valid());
1087         return object_->data.picture.data;
1088      }
1089 
1090      void Picture::set_type(::FLAC__StreamMetadata_Picture_Type type)
1091      {
1092         FLAC__ASSERT(is_valid());
1093         object_->data.picture.type = type;
1094      }
1095 
1096      bool Picture::set_mime_type(const char *string)
1097      {
1098         FLAC__ASSERT(is_valid());
1099         // We can safely const_cast since copy=true
1100         return (bool)::FLAC__metadata_object_picture_set_mime_type(object_, const_cast<char*>(string), /*copy=*/true);
1101      }
1102 
1103      bool Picture::set_description(const FLAC__byte *string)
1104      {
1105         FLAC__ASSERT(is_valid());
1106         // We can safely const_cast since copy=true
1107         return (bool)::FLAC__metadata_object_picture_set_description(object_, const_cast<FLAC__byte*>(string), /*copy=*/true);
1108      }
1109 
1110      void Picture::set_width(FLAC__uint32 value) const
1111      {
1112         FLAC__ASSERT(is_valid());
1113         object_->data.picture.width = value;
1114      }
1115 
1116      void Picture::set_height(FLAC__uint32 value) const
1117      {
1118         FLAC__ASSERT(is_valid());
1119         object_->data.picture.height = value;
1120      }
1121 
1122      void Picture::set_depth(FLAC__uint32 value) const
1123      {
1124         FLAC__ASSERT(is_valid());
1125         object_->data.picture.depth = value;
1126      }
1127 
1128      void Picture::set_colors(FLAC__uint32 value) const
1129      {
1130         FLAC__ASSERT(is_valid());
1131         object_->data.picture.colors = value;
1132      }
1133 
1134      bool Picture::set_data(const FLAC__byte *data, FLAC__uint32 data_length)
1135      {
1136         FLAC__ASSERT(is_valid());
1137         // We can safely const_cast since copy=true
1138         return (bool)::FLAC__metadata_object_picture_set_data(object_, const_cast<FLAC__byte*>(data), data_length, /*copy=*/true);
1139      }
1140 
1141 
1142      //
1143      // Unknown
1144      //
1145 
1146      Unknown::Unknown():
1147      Prototype(FLAC__metadata_object_new(FLAC__METADATA_TYPE_APPLICATION), /*copy=*/false)
1148      { }
1149 
1150      Unknown::~Unknown()
1151      { }
1152 
1153      const FLAC__byte *Unknown::get_data() const
1154      {
1155         FLAC__ASSERT(is_valid());
1156         return object_->data.application.data;
1157      }
1158 
1159      bool Unknown::set_data(const FLAC__byte *data, unsigned length)
1160      {
1161         FLAC__ASSERT(is_valid());
1162         return (bool)::FLAC__metadata_object_application_set_data(object_, (FLAC__byte*)data, length, true);
1163      }
1164 
1165      bool Unknown::set_data(FLAC__byte *data, unsigned length, bool copy)
1166      {
1167         FLAC__ASSERT(is_valid());
1168         return (bool)::FLAC__metadata_object_application_set_data(object_, data, length, copy);
1169      }
1170 
1171 
1172      // ============================================================
1173      //
1174      //  Level 0
1175      //
1176      // ============================================================
1177 
1178      FLACPP_API bool get_streaminfo(const char *filename, StreamInfo &streaminfo)
1179      {
1180         FLAC__ASSERT(0 != filename);
1181 
1182         ::FLAC__StreamMetadata object;
1183 
1184         if(::FLAC__metadata_get_streaminfo(filename, &object)) {
1185            streaminfo = object;
1186            return true;
1187         }
1188         else
1189            return false;
1190      }
1191 
1192      FLACPP_API bool get_tags(const char *filename, VorbisComment *&tags)
1193      {
1194         FLAC__ASSERT(0 != filename);
1195 
1196         ::FLAC__StreamMetadata *object;
1197 
1198         tags = 0;
1199 
1200         if(::FLAC__metadata_get_tags(filename, &object)) {
1201            tags = new VorbisComment(object, /*copy=*/false);
1202            return true;
1203         }
1204         else
1205            return false;
1206      }
1207 
1208      FLACPP_API bool get_tags(const char *filename, VorbisComment &tags)
1209      {
1210         FLAC__ASSERT(0 != filename);
1211 
1212         ::FLAC__StreamMetadata *object;
1213 
1214         if(::FLAC__metadata_get_tags(filename, &object)) {
1215            tags.assign(object, /*copy=*/false);
1216            return true;
1217         }
1218         else
1219            return false;
1220      }
1221 
1222      FLACPP_API bool get_cuesheet(const char *filename, CueSheet *&cuesheet)
1223      {
1224         FLAC__ASSERT(0 != filename);
1225 
1226         ::FLAC__StreamMetadata *object;
1227 
1228         cuesheet = 0;
1229 
1230         if(::FLAC__metadata_get_cuesheet(filename, &object)) {
1231            cuesheet = new CueSheet(object, /*copy=*/false);
1232            return true;
1233         }
1234         else
1235            return false;
1236      }
1237 
1238      FLACPP_API bool get_cuesheet(const char *filename, CueSheet &cuesheet)
1239      {
1240         FLAC__ASSERT(0 != filename);
1241 
1242         ::FLAC__StreamMetadata *object;
1243 
1244         if(::FLAC__metadata_get_cuesheet(filename, &object)) {
1245            cuesheet.assign(object, /*copy=*/false);
1246            return true;
1247         }
1248         else
1249            return false;
1250      }
1251 
1252      FLACPP_API bool get_picture(const char *filename, Picture *&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)
1253      {
1254         FLAC__ASSERT(0 != filename);
1255 
1256         ::FLAC__StreamMetadata *object;
1257 
1258         picture = 0;
1259 
1260         if(::FLAC__metadata_get_picture(filename, &object, type, mime_type, description, max_width, max_height, max_depth, max_colors)) {
1261            picture = new Picture(object, /*copy=*/false);
1262            return true;
1263         }
1264         else
1265            return false;
1266      }
1267 
1268      FLACPP_API bool get_picture(const char *filename, Picture &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)
1269      {
1270         FLAC__ASSERT(0 != filename);
1271 
1272         ::FLAC__StreamMetadata *object;
1273 
1274         if(::FLAC__metadata_get_picture(filename, &object, type, mime_type, description, max_width, max_height, max_depth, max_colors)) {
1275            picture.assign(object, /*copy=*/false);
1276            return true;
1277         }
1278         else
1279            return false;
1280      }
1281 
1282 
1283      // ============================================================
1284      //
1285      //  Level 1
1286      //
1287      // ============================================================
1288 
1289      SimpleIterator::SimpleIterator():
1290      iterator_(::FLAC__metadata_simple_iterator_new())
1291      { }
1292 
1293      SimpleIterator::~SimpleIterator()
1294      {
1295         clear();
1296      }
1297 
1298      void SimpleIterator::clear()
1299      {
1300         if(0 != iterator_)
1301            FLAC__metadata_simple_iterator_delete(iterator_);
1302         iterator_ = 0;
1303      }
1304 
1305      bool SimpleIterator::init(const char *filename, bool read_only, bool preserve_file_stats)
1306      {
1307         FLAC__ASSERT(0 != filename);
1308         FLAC__ASSERT(is_valid());
1309         return (bool)::FLAC__metadata_simple_iterator_init(iterator_, filename, read_only, preserve_file_stats);
1310      }
1311 
1312      bool SimpleIterator::is_valid() const
1313      {
1314         return 0 != iterator_;
1315      }
1316 
1317      SimpleIterator::Status SimpleIterator::status()
1318      {
1319         FLAC__ASSERT(is_valid());
1320         return Status(::FLAC__metadata_simple_iterator_status(iterator_));
1321      }
1322 
1323      bool SimpleIterator::is_writable() const
1324      {
1325         FLAC__ASSERT(is_valid());
1326         return (bool)::FLAC__metadata_simple_iterator_is_writable(iterator_);
1327      }
1328 
1329      bool SimpleIterator::next()
1330      {
1331         FLAC__ASSERT(is_valid());
1332         return (bool)::FLAC__metadata_simple_iterator_next(iterator_);
1333      }
1334 
1335      bool SimpleIterator::prev()
1336      {
1337         FLAC__ASSERT(is_valid());
1338         return (bool)::FLAC__metadata_simple_iterator_prev(iterator_);
1339      }
1340 
1341      //@@@@ add to tests
1342      bool SimpleIterator::is_last() const
1343      {
1344         FLAC__ASSERT(is_valid());
1345         return (bool)::FLAC__metadata_simple_iterator_is_last(iterator_);
1346      }
1347 
1348      //@@@@ add to tests
1349      off_t SimpleIterator::get_block_offset() const
1350      {
1351         FLAC__ASSERT(is_valid());
1352         return ::FLAC__metadata_simple_iterator_get_block_offset(iterator_);
1353      }
1354 
1355      ::FLAC__MetadataType SimpleIterator::get_block_type() const
1356      {
1357         FLAC__ASSERT(is_valid());
1358         return ::FLAC__metadata_simple_iterator_get_block_type(iterator_);
1359      }
1360 
1361      //@@@@ add to tests
1362      unsigned SimpleIterator::get_block_length() const
1363      {
1364         FLAC__ASSERT(is_valid());
1365         return ::FLAC__metadata_simple_iterator_get_block_length(iterator_);
1366      }
1367 
1368      //@@@@ add to tests
1369      bool SimpleIterator::get_application_id(FLAC__byte *id)
1370      {
1371         FLAC__ASSERT(is_valid());
1372         return (bool)::FLAC__metadata_simple_iterator_get_application_id(iterator_, id);
1373      }
1374 
1375      Prototype *SimpleIterator::get_block()
1376      {
1377         FLAC__ASSERT(is_valid());
1378         return local::construct_block(::FLAC__metadata_simple_iterator_get_block(iterator_));
1379      }
1380 
1381      bool SimpleIterator::set_block(Prototype *block, bool use_padding)
1382      {
1383         FLAC__ASSERT(0 != block);
1384         FLAC__ASSERT(is_valid());
1385         return (bool)::FLAC__metadata_simple_iterator_set_block(iterator_, block->object_, use_padding);
1386      }
1387 
1388      bool SimpleIterator::insert_block_after(Prototype *block, bool use_padding)
1389      {
1390         FLAC__ASSERT(0 != block);
1391         FLAC__ASSERT(is_valid());
1392         return (bool)::FLAC__metadata_simple_iterator_insert_block_after(iterator_, block->object_, use_padding);
1393      }
1394 
1395      bool SimpleIterator::delete_block(bool use_padding)
1396      {
1397         FLAC__ASSERT(is_valid());
1398         return (bool)::FLAC__metadata_simple_iterator_delete_block(iterator_, use_padding);
1399      }
1400 
1401 
1402      // ============================================================
1403      //
1404      //  Level 2
1405      //
1406      // ============================================================
1407 
1408      Chain::Chain():
1409      chain_(::FLAC__metadata_chain_new())
1410      { }
1411 
1412      Chain::~Chain()
1413      {
1414         clear();
1415      }
1416 
1417      void Chain::clear()
1418      {
1419         if(0 != chain_)
1420            FLAC__metadata_chain_delete(chain_);
1421         chain_ = 0;
1422      }
1423 
1424      bool Chain::is_valid() const
1425      {
1426         return 0 != chain_;
1427      }
1428 
1429      Chain::Status Chain::status()
1430      {
1431         FLAC__ASSERT(is_valid());
1432         return Status(::FLAC__metadata_chain_status(chain_));
1433      }
1434 
1435      bool Chain::read(const char *filename, bool is_ogg)
1436      {
1437         FLAC__ASSERT(0 != filename);
1438         FLAC__ASSERT(is_valid());
1439         return is_ogg?
1440            (bool)::FLAC__metadata_chain_read_ogg(chain_, filename) :
1441            (bool)::FLAC__metadata_chain_read(chain_, filename)
1442         ;
1443      }
1444 
1445      bool Chain::read(FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks, bool is_ogg)
1446      {
1447         FLAC__ASSERT(is_valid());
1448         return is_ogg?
1449            (bool)::FLAC__metadata_chain_read_ogg_with_callbacks(chain_, handle, callbacks) :
1450            (bool)::FLAC__metadata_chain_read_with_callbacks(chain_, handle, callbacks)
1451         ;
1452      }
1453 
1454      bool Chain::check_if_tempfile_needed(bool use_padding)
1455      {
1456         FLAC__ASSERT(is_valid());
1457         return (bool)::FLAC__metadata_chain_check_if_tempfile_needed(chain_, use_padding);
1458      }
1459 
1460      bool Chain::write(bool use_padding, bool preserve_file_stats)
1461      {
1462         FLAC__ASSERT(is_valid());
1463         return (bool)::FLAC__metadata_chain_write(chain_, use_padding, preserve_file_stats);
1464      }
1465 
1466      bool Chain::write(bool use_padding, ::FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks)
1467      {
1468         FLAC__ASSERT(is_valid());
1469         return (bool)::FLAC__metadata_chain_write_with_callbacks(chain_, use_padding, handle, callbacks);
1470      }
1471 
1472      bool Chain::write(bool use_padding, ::FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks, ::FLAC__IOHandle temp_handle, ::FLAC__IOCallbacks temp_callbacks)
1473      {
1474         FLAC__ASSERT(is_valid());
1475         return (bool)::FLAC__metadata_chain_write_with_callbacks_and_tempfile(chain_, use_padding, handle, callbacks, temp_handle, temp_callbacks);
1476      }
1477 
1478      void Chain::merge_padding()
1479      {
1480         FLAC__ASSERT(is_valid());
1481         ::FLAC__metadata_chain_merge_padding(chain_);
1482      }
1483 
1484      void Chain::sort_padding()
1485      {
1486         FLAC__ASSERT(is_valid());
1487         ::FLAC__metadata_chain_sort_padding(chain_);
1488      }
1489 
1490 
1491      Iterator::Iterator():
1492      iterator_(::FLAC__metadata_iterator_new())
1493      { }
1494 
1495      Iterator::~Iterator()
1496      {
1497         clear();
1498      }
1499 
1500      void Iterator::clear()
1501      {
1502         if(0 != iterator_)
1503            FLAC__metadata_iterator_delete(iterator_);
1504         iterator_ = 0;
1505      }
1506 
1507      bool Iterator::is_valid() const
1508      {
1509         return 0 != iterator_;
1510      }
1511 
1512      void Iterator::init(Chain &chain)
1513      {
1514         FLAC__ASSERT(is_valid());
1515         FLAC__ASSERT(chain.is_valid());
1516         ::FLAC__metadata_iterator_init(iterator_, chain.chain_);
1517      }
1518 
1519      bool Iterator::next()
1520      {
1521         FLAC__ASSERT(is_valid());
1522         return (bool)::FLAC__metadata_iterator_next(iterator_);
1523      }
1524 
1525      bool Iterator::prev()
1526      {
1527         FLAC__ASSERT(is_valid());
1528         return (bool)::FLAC__metadata_iterator_prev(iterator_);
1529      }
1530 
1531      ::FLAC__MetadataType Iterator::get_block_type() const
1532      {
1533         FLAC__ASSERT(is_valid());
1534         return ::FLAC__metadata_iterator_get_block_type(iterator_);
1535      }
1536 
1537      Prototype *Iterator::get_block()
1538      {
1539         FLAC__ASSERT(is_valid());
1540         Prototype *block = local::construct_block(::FLAC__metadata_iterator_get_block(iterator_));
1541         if(0 != block)
1542            block->set_reference(true);
1543         return block;
1544      }
1545 
1546      bool Iterator::set_block(Prototype *block)
1547      {
1548         FLAC__ASSERT(0 != block);
1549         FLAC__ASSERT(is_valid());
1550         bool ret = (bool)::FLAC__metadata_iterator_set_block(iterator_, block->object_);
1551         if(ret) {
1552            block->set_reference(true);
1553            delete block;
1554         }
1555         return ret;
1556      }
1557 
1558      bool Iterator::delete_block(bool replace_with_padding)
1559      {
1560         FLAC__ASSERT(is_valid());
1561         return (bool)::FLAC__metadata_iterator_delete_block(iterator_, replace_with_padding);
1562      }
1563 
1564      bool Iterator::insert_block_before(Prototype *block)
1565      {
1566         FLAC__ASSERT(0 != block);
1567         FLAC__ASSERT(is_valid());
1568         bool ret = (bool)::FLAC__metadata_iterator_insert_block_before(iterator_, block->object_);
1569         if(ret) {
1570            block->set_reference(true);
1571            delete block;
1572         }
1573         return ret;
1574      }
1575 
1576      bool Iterator::insert_block_after(Prototype *block)
1577      {
1578         FLAC__ASSERT(0 != block);
1579         FLAC__ASSERT(is_valid());
1580         bool ret = (bool)::FLAC__metadata_iterator_insert_block_after(iterator_, block->object_);
1581         if(ret) {
1582            block->set_reference(true);
1583            delete block;
1584         }
1585         return ret;
1586      }
1587 
1588   }
1589}
src/lib/libflac/libflac++/stream_decoder.cpp
r0r14135
1/* libFLAC++ - Free Lossless Audio Codec library
2 * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31 
32#include "flac++/decoder.h"
33#include "flac/assert.h"
34 
35#ifdef _MSC_VER
36// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning)
37#pragma warning ( disable : 4800 )
38#endif
39 
40namespace FLAC {
41   namespace Decoder {
42 
43      // ------------------------------------------------------------
44      //
45      // Stream
46      //
47      // ------------------------------------------------------------
48 
49      Stream::Stream():
50      decoder_(::FLAC__stream_decoder_new())
51      { }
52 
53      Stream::~Stream()
54      {
55         if(0 != decoder_) {
56            (void)::FLAC__stream_decoder_finish(decoder_);
57            ::FLAC__stream_decoder_delete(decoder_);
58         }
59      }
60 
61      bool Stream::is_valid() const
62      {
63         return 0 != decoder_;
64      }
65 
66      bool Stream::set_ogg_serial_number(long value)
67      {
68         FLAC__ASSERT(is_valid());
69         return (bool)::FLAC__stream_decoder_set_ogg_serial_number(decoder_, value);
70      }
71 
72      bool Stream::set_md5_checking(bool value)
73      {
74         FLAC__ASSERT(is_valid());
75         return (bool)::FLAC__stream_decoder_set_md5_checking(decoder_, value);
76      }
77 
78      bool Stream::set_metadata_respond(::FLAC__MetadataType type)
79      {
80         FLAC__ASSERT(is_valid());
81         return (bool)::FLAC__stream_decoder_set_metadata_respond(decoder_, type);
82      }
83 
84      bool Stream::set_metadata_respond_application(const FLAC__byte id[4])
85      {
86         FLAC__ASSERT(is_valid());
87         return (bool)::FLAC__stream_decoder_set_metadata_respond_application(decoder_, id);
88      }
89 
90      bool Stream::set_metadata_respond_all()
91      {
92         FLAC__ASSERT(is_valid());
93         return (bool)::FLAC__stream_decoder_set_metadata_respond_all(decoder_);
94      }
95 
96      bool Stream::set_metadata_ignore(::FLAC__MetadataType type)
97      {
98         FLAC__ASSERT(is_valid());
99         return (bool)::FLAC__stream_decoder_set_metadata_ignore(decoder_, type);
100      }
101 
102      bool Stream::set_metadata_ignore_application(const FLAC__byte id[4])
103      {
104         FLAC__ASSERT(is_valid());
105         return (bool)::FLAC__stream_decoder_set_metadata_ignore_application(decoder_, id);
106      }
107 
108      bool Stream::set_metadata_ignore_all()
109      {
110         FLAC__ASSERT(is_valid());
111         return (bool)::FLAC__stream_decoder_set_metadata_ignore_all(decoder_);
112      }
113 
114      Stream::State Stream::get_state() const
115      {
116         FLAC__ASSERT(is_valid());
117         return State(::FLAC__stream_decoder_get_state(decoder_));
118      }
119 
120      bool Stream::get_md5_checking() const
121      {
122         FLAC__ASSERT(is_valid());
123         return (bool)::FLAC__stream_decoder_get_md5_checking(decoder_);
124      }
125 
126      FLAC__uint64 Stream::get_total_samples() const
127      {
128         FLAC__ASSERT(is_valid());
129         return ::FLAC__stream_decoder_get_total_samples(decoder_);
130      }
131 
132      unsigned Stream::get_channels() const
133      {
134         FLAC__ASSERT(is_valid());
135         return ::FLAC__stream_decoder_get_channels(decoder_);
136      }
137 
138      ::FLAC__ChannelAssignment Stream::get_channel_assignment() const
139      {
140         FLAC__ASSERT(is_valid());
141         return ::FLAC__stream_decoder_get_channel_assignment(decoder_);
142      }
143 
144      unsigned Stream::get_bits_per_sample() const
145      {
146         FLAC__ASSERT(is_valid());
147         return ::FLAC__stream_decoder_get_bits_per_sample(decoder_);
148      }
149 
150      unsigned Stream::get_sample_rate() const
151      {
152         FLAC__ASSERT(is_valid());
153         return ::FLAC__stream_decoder_get_sample_rate(decoder_);
154      }
155 
156      unsigned Stream::get_blocksize() const
157      {
158         FLAC__ASSERT(is_valid());
159         return ::FLAC__stream_decoder_get_blocksize(decoder_);
160      }
161 
162      bool Stream::get_decode_position(FLAC__uint64 *position) const
163      {
164         FLAC__ASSERT(is_valid());
165         return ::FLAC__stream_decoder_get_decode_position(decoder_, position);
166      }
167 
168      ::FLAC__StreamDecoderInitStatus Stream::init()
169      {
170         FLAC__ASSERT(is_valid());
171         return ::FLAC__stream_decoder_init_stream(decoder_, read_callback_, seek_callback_, tell_callback_, length_callback_, eof_callback_, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this);
172      }
173 
174      ::FLAC__StreamDecoderInitStatus Stream::init_ogg()
175      {
176         FLAC__ASSERT(is_valid());
177         return ::FLAC__stream_decoder_init_ogg_stream(decoder_, read_callback_, seek_callback_, tell_callback_, length_callback_, eof_callback_, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this);
178      }
179 
180      bool Stream::finish()
181      {
182         FLAC__ASSERT(is_valid());
183         return (bool)::FLAC__stream_decoder_finish(decoder_);
184      }
185 
186      bool Stream::flush()
187      {
188         FLAC__ASSERT(is_valid());
189         return (bool)::FLAC__stream_decoder_flush(decoder_);
190      }
191 
192      bool Stream::reset()
193      {
194         FLAC__ASSERT(is_valid());
195         return (bool)::FLAC__stream_decoder_reset(decoder_);
196      }
197 
198      bool Stream::process_single()
199      {
200         FLAC__ASSERT(is_valid());
201         return (bool)::FLAC__stream_decoder_process_single(decoder_);
202      }
203 
204      bool Stream::process_until_end_of_metadata()
205      {
206         FLAC__ASSERT(is_valid());
207         return (bool)::FLAC__stream_decoder_process_until_end_of_metadata(decoder_);
208      }
209 
210      bool Stream::process_until_end_of_stream()
211      {
212         FLAC__ASSERT(is_valid());
213         return (bool)::FLAC__stream_decoder_process_until_end_of_stream(decoder_);
214      }
215 
216      bool Stream::skip_single_frame()
217      {
218         FLAC__ASSERT(is_valid());
219         return (bool)::FLAC__stream_decoder_skip_single_frame(decoder_);
220      }
221 
222      bool Stream::seek_absolute(FLAC__uint64 sample)
223      {
224         FLAC__ASSERT(is_valid());
225         return (bool)::FLAC__stream_decoder_seek_absolute(decoder_, sample);
226      }
227 
228      ::FLAC__StreamDecoderSeekStatus Stream::seek_callback(FLAC__uint64 absolute_byte_offset)
229      {
230         (void)absolute_byte_offset;
231         return ::FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
232      }
233 
234      ::FLAC__StreamDecoderTellStatus Stream::tell_callback(FLAC__uint64 *absolute_byte_offset)
235      {
236         (void)absolute_byte_offset;
237         return ::FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
238      }
239 
240      ::FLAC__StreamDecoderLengthStatus Stream::length_callback(FLAC__uint64 *stream_length)
241      {
242         (void)stream_length;
243         return ::FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
244      }
245 
246      bool Stream::eof_callback()
247      {
248         return false;
249      }
250 
251      void Stream::metadata_callback(const ::FLAC__StreamMetadata *metadata)
252      {
253         (void)metadata;
254      }
255 
256      ::FLAC__StreamDecoderReadStatus Stream::read_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
257      {
258         (void)decoder;
259         FLAC__ASSERT(0 != client_data);
260         Stream *instance = reinterpret_cast<Stream *>(client_data);
261         FLAC__ASSERT(0 != instance);
262         return instance->read_callback(buffer, bytes);
263      }
264 
265      ::FLAC__StreamDecoderSeekStatus Stream::seek_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
266      {
267         (void) decoder;
268         FLAC__ASSERT(0 != client_data);
269         Stream *instance = reinterpret_cast<Stream *>(client_data);
270         FLAC__ASSERT(0 != instance);
271         return instance->seek_callback(absolute_byte_offset);
272      }
273 
274      ::FLAC__StreamDecoderTellStatus Stream::tell_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
275      {
276         (void) decoder;
277         FLAC__ASSERT(0 != client_data);
278         Stream *instance = reinterpret_cast<Stream *>(client_data);
279         FLAC__ASSERT(0 != instance);
280         return instance->tell_callback(absolute_byte_offset);
281      }
282 
283      ::FLAC__StreamDecoderLengthStatus Stream::length_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
284      {
285         (void) decoder;
286         FLAC__ASSERT(0 != client_data);
287         Stream *instance = reinterpret_cast<Stream *>(client_data);
288         FLAC__ASSERT(0 != instance);
289         return instance->length_callback(stream_length);
290      }
291 
292      FLAC__bool Stream::eof_callback_(const ::FLAC__StreamDecoder *decoder, void *client_data)
293      {
294         (void) decoder;
295         FLAC__ASSERT(0 != client_data);
296         Stream *instance = reinterpret_cast<Stream *>(client_data);
297         FLAC__ASSERT(0 != instance);
298         return instance->eof_callback();
299      }
300 
301      ::FLAC__StreamDecoderWriteStatus Stream::write_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
302      {
303         (void)decoder;
304         FLAC__ASSERT(0 != client_data);
305         Stream *instance = reinterpret_cast<Stream *>(client_data);
306         FLAC__ASSERT(0 != instance);
307         return instance->write_callback(frame, buffer);
308      }
309 
310      void Stream::metadata_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *client_data)
311      {
312         (void)decoder;
313         FLAC__ASSERT(0 != client_data);
314         Stream *instance = reinterpret_cast<Stream *>(client_data);
315         FLAC__ASSERT(0 != instance);
316         instance->metadata_callback(metadata);
317      }
318 
319      void Stream::error_callback_(const ::FLAC__StreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *client_data)
320      {
321         (void)decoder;
322         FLAC__ASSERT(0 != client_data);
323         Stream *instance = reinterpret_cast<Stream *>(client_data);
324         FLAC__ASSERT(0 != instance);
325         instance->error_callback(status);
326      }
327 
328      // ------------------------------------------------------------
329      //
330      // File
331      //
332      // ------------------------------------------------------------
333 
334      File::File():
335         Stream()
336      { }
337 
338      File::~File()
339      {
340      }
341 
342      ::FLAC__StreamDecoderInitStatus File::init(FILE *file)
343      {
344         FLAC__ASSERT(0 != decoder_);
345         return ::FLAC__stream_decoder_init_FILE(decoder_, file, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this);
346      }
347 
348      ::FLAC__StreamDecoderInitStatus File::init(const char *filename)
349      {
350         FLAC__ASSERT(0 != decoder_);
351         return ::FLAC__stream_decoder_init_file(decoder_, filename, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this);
352      }
353 
354      ::FLAC__StreamDecoderInitStatus File::init(const std::string &filename)
355      {
356         return init(filename.c_str());
357      }
358 
359      ::FLAC__StreamDecoderInitStatus File::init_ogg(FILE *file)
360      {
361         FLAC__ASSERT(0 != decoder_);
362         return ::FLAC__stream_decoder_init_ogg_FILE(decoder_, file, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this);
363      }
364 
365      ::FLAC__StreamDecoderInitStatus File::init_ogg(const char *filename)
366      {
367         FLAC__ASSERT(0 != decoder_);
368         return ::FLAC__stream_decoder_init_ogg_file(decoder_, filename, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this);
369      }
370 
371      ::FLAC__StreamDecoderInitStatus File::init_ogg(const std::string &filename)
372      {
373         return init_ogg(filename.c_str());
374      }
375 
376      // This is a dummy to satisfy the pure virtual from Stream; the
377      // read callback will never be called since we are initializing
378      // with FLAC__stream_decoder_init_FILE() or
379      // FLAC__stream_decoder_init_file() and those supply the read
380      // callback internally.
381      ::FLAC__StreamDecoderReadStatus File::read_callback(FLAC__byte buffer[], size_t *bytes)
382      {
383         (void)buffer, (void)bytes;
384         FLAC__ASSERT(false);
385         return ::FLAC__STREAM_DECODER_READ_STATUS_ABORT; // double protection
386      }
387 
388   }
389}
src/lib/libflac/libflac++/stream_encoder.cpp
r0r14135
1/* libFLAC++ - Free Lossless Audio Codec library
2 * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31 
32#include "flac++/encoder.h"
33#include "flac++/metadata.h"
34#include "flac/assert.h"
35 
36#ifdef _MSC_VER
37// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning)
38#pragma warning ( disable : 4800 )
39#endif
40 
41namespace FLAC {
42   namespace Encoder {
43 
44      // ------------------------------------------------------------
45      //
46      // Stream
47      //
48      // ------------------------------------------------------------
49 
50      Stream::Stream():
51      encoder_(::FLAC__stream_encoder_new())
52      { }
53 
54      Stream::~Stream()
55      {
56         if(0 != encoder_) {
57            (void)::FLAC__stream_encoder_finish(encoder_);
58            ::FLAC__stream_encoder_delete(encoder_);
59         }
60      }
61 
62      bool Stream::is_valid() const
63      {
64         return 0 != encoder_;
65      }
66 
67      bool Stream::set_ogg_serial_number(long value)
68      {
69         FLAC__ASSERT(is_valid());
70         return (bool)::FLAC__stream_encoder_set_ogg_serial_number(encoder_, value);
71      }
72 
73      bool Stream::set_verify(bool value)
74      {
75         FLAC__ASSERT(is_valid());
76         return (bool)::FLAC__stream_encoder_set_verify(encoder_, value);
77      }
78 
79      bool Stream::set_streamable_subset(bool value)
80      {
81         FLAC__ASSERT(is_valid());
82         return (bool)::FLAC__stream_encoder_set_streamable_subset(encoder_, value);
83      }
84 
85      bool Stream::set_channels(unsigned value)
86      {
87         FLAC__ASSERT(is_valid());
88         return (bool)::FLAC__stream_encoder_set_channels(encoder_, value);
89      }
90 
91      bool Stream::set_bits_per_sample(unsigned value)
92      {
93         FLAC__ASSERT(is_valid());
94         return (bool)::FLAC__stream_encoder_set_bits_per_sample(encoder_, value);
95      }
96 
97      bool Stream::set_sample_rate(unsigned value)
98      {
99         FLAC__ASSERT(is_valid());
100         return (bool)::FLAC__stream_encoder_set_sample_rate(encoder_, value);
101      }
102 
103      bool Stream::set_compression_level(unsigned value)
104      {
105         FLAC__ASSERT(is_valid());
106         return (bool)::FLAC__stream_encoder_set_compression_level(encoder_, value);
107      }
108 
109      bool Stream::set_blocksize(unsigned value)
110      {
111         FLAC__ASSERT(is_valid());
112         return (bool)::FLAC__stream_encoder_set_blocksize(encoder_, value);
113      }
114 
115      bool Stream::set_do_mid_side_stereo(bool value)
116      {
117         FLAC__ASSERT(is_valid());
118         return (bool)::FLAC__stream_encoder_set_do_mid_side_stereo(encoder_, value);
119      }
120 
121      bool Stream::set_loose_mid_side_stereo(bool value)
122      {
123         FLAC__ASSERT(is_valid());
124         return (bool)::FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_, value);
125      }
126 
127      bool Stream::set_apodization(const char *specification)
128      {
129         FLAC__ASSERT(is_valid());
130         return (bool)::FLAC__stream_encoder_set_apodization(encoder_, specification);
131      }
132 
133      bool Stream::set_max_lpc_order(unsigned value)
134      {
135         FLAC__ASSERT(is_valid());
136         return (bool)::FLAC__stream_encoder_set_max_lpc_order(encoder_, value);
137      }
138 
139      bool Stream::set_qlp_coeff_precision(unsigned value)
140      {
141         FLAC__ASSERT(is_valid());
142         return (bool)::FLAC__stream_encoder_set_qlp_coeff_precision(encoder_, value);
143      }
144 
145      bool Stream::set_do_qlp_coeff_prec_search(bool value)
146      {
147         FLAC__ASSERT(is_valid());
148         return (bool)::FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_, value);
149      }
150 
151      bool Stream::set_do_escape_coding(bool value)
152      {
153         FLAC__ASSERT(is_valid());
154         return (bool)::FLAC__stream_encoder_set_do_escape_coding(encoder_, value);
155      }
156 
157      bool Stream::set_do_exhaustive_model_search(bool value)
158      {
159         FLAC__ASSERT(is_valid());
160         return (bool)::FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_, value);
161      }
162 
163      bool Stream::set_min_residual_partition_order(unsigned value)
164      {
165         FLAC__ASSERT(is_valid());
166         return (bool)::FLAC__stream_encoder_set_min_residual_partition_order(encoder_, value);
167      }
168 
169      bool Stream::set_max_residual_partition_order(unsigned value)
170      {
171         FLAC__ASSERT(is_valid());
172         return (bool)::FLAC__stream_encoder_set_max_residual_partition_order(encoder_, value);
173      }
174 
175      bool Stream::set_rice_parameter_search_dist(unsigned value)
176      {
177         FLAC__ASSERT(is_valid());
178         return (bool)::FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_, value);
179      }
180 
181      bool Stream::set_total_samples_estimate(FLAC__uint64 value)
182      {
183         FLAC__ASSERT(is_valid());
184         return (bool)::FLAC__stream_encoder_set_total_samples_estimate(encoder_, value);
185      }
186 
187      bool Stream::set_metadata(::FLAC__StreamMetadata **metadata, unsigned num_blocks)
188      {
189         FLAC__ASSERT(is_valid());
190         return (bool)::FLAC__stream_encoder_set_metadata(encoder_, metadata, num_blocks);
191      }
192 
193      bool Stream::set_metadata(FLAC::Metadata::Prototype **metadata, unsigned num_blocks)
194      {
195         FLAC__ASSERT(is_valid());
196#if (defined _MSC_VER) || (defined __BORLANDC__) || (defined __SUNPRO_CC)
197         // MSVC++ can't handle:
198         // ::FLAC__StreamMetadata *m[num_blocks];
199         // so we do this ugly workaround
200         ::FLAC__StreamMetadata **m = new ::FLAC__StreamMetadata*[num_blocks];
201#else
202         ::FLAC__StreamMetadata *m[num_blocks];
203#endif
204         for(unsigned i = 0; i < num_blocks; i++) {
205            // we can get away with the const_cast since we know the encoder will only correct the is_last flags
206            m[i] = const_cast< ::FLAC__StreamMetadata*>((const ::FLAC__StreamMetadata*)metadata[i]);
207         }
208#if (defined _MSC_VER) || (defined __BORLANDC__) || (defined __SUNPRO_CC)
209         // complete the hack
210         const bool ok = (bool)::FLAC__stream_encoder_set_metadata(encoder_, m, num_blocks);
211         delete [] m;
212         return ok;
213#else
214         return (bool)::FLAC__stream_encoder_set_metadata(encoder_, m, num_blocks);
215#endif
216      }
217 
218      Stream::State Stream::get_state() const
219      {
220         FLAC__ASSERT(is_valid());
221         return State(::FLAC__stream_encoder_get_state(encoder_));
222      }
223 
224      Decoder::Stream::State Stream::get_verify_decoder_state() const
225      {
226         FLAC__ASSERT(is_valid());
227         return Decoder::Stream::State(::FLAC__stream_encoder_get_verify_decoder_state(encoder_));
228      }
229 
230      void Stream::get_verify_decoder_error_stats(FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got)
231      {
232         FLAC__ASSERT(is_valid());
233         ::FLAC__stream_encoder_get_verify_decoder_error_stats(encoder_, absolute_sample, frame_number, channel, sample, expected, got);
234      }
235 
236      bool Stream::get_verify() const
237      {
238         FLAC__ASSERT(is_valid());
239         return (bool)::FLAC__stream_encoder_get_verify(encoder_);
240      }
241 
242      bool Stream::get_streamable_subset() const
243      {
244         FLAC__ASSERT(is_valid());
245         return (bool)::FLAC__stream_encoder_get_streamable_subset(encoder_);
246      }
247 
248      bool Stream::get_do_mid_side_stereo() const
249      {
250         FLAC__ASSERT(is_valid());
251         return (bool)::FLAC__stream_encoder_get_do_mid_side_stereo(encoder_);
252      }
253 
254      bool Stream::get_loose_mid_side_stereo() const
255      {
256         FLAC__ASSERT(is_valid());
257         return (bool)::FLAC__stream_encoder_get_loose_mid_side_stereo(encoder_);
258      }
259 
260      unsigned Stream::get_channels() const
261      {
262         FLAC__ASSERT(is_valid());
263         return ::FLAC__stream_encoder_get_channels(encoder_);
264      }
265 
266      unsigned Stream::get_bits_per_sample() const
267      {
268         FLAC__ASSERT(is_valid());
269         return ::FLAC__stream_encoder_get_bits_per_sample(encoder_);
270      }
271 
272      unsigned Stream::get_sample_rate() const
273      {
274         FLAC__ASSERT(is_valid());
275         return ::FLAC__stream_encoder_get_sample_rate(encoder_);
276      }
277 
278      unsigned Stream::get_blocksize() const
279      {
280         FLAC__ASSERT(is_valid());
281         return ::FLAC__stream_encoder_get_blocksize(encoder_);
282      }
283 
284      unsigned Stream::get_max_lpc_order() const
285      {
286         FLAC__ASSERT(is_valid());
287         return ::FLAC__stream_encoder_get_max_lpc_order(encoder_);
288      }
289 
290      unsigned Stream::get_qlp_coeff_precision() const
291      {
292         FLAC__ASSERT(is_valid());
293         return ::FLAC__stream_encoder_get_qlp_coeff_precision(encoder_);
294      }
295 
296      bool Stream::get_do_qlp_coeff_prec_search() const
297      {
298         FLAC__ASSERT(is_valid());
299         return (bool)::FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder_);
300      }
301 
302      bool Stream::get_do_escape_coding() const
303      {
304         FLAC__ASSERT(is_valid());
305         return (bool)::FLAC__stream_encoder_get_do_escape_coding(encoder_);
306      }
307 
308      bool Stream::get_do_exhaustive_model_search() const
309      {
310         FLAC__ASSERT(is_valid());
311         return (bool)::FLAC__stream_encoder_get_do_exhaustive_model_search(encoder_);
312      }
313 
314      unsigned Stream::get_min_residual_partition_order() const
315      {
316         FLAC__ASSERT(is_valid());
317         return ::FLAC__stream_encoder_get_min_residual_partition_order(encoder_);
318      }
319 
320      unsigned Stream::get_max_residual_partition_order() const
321      {
322         FLAC__ASSERT(is_valid());
323         return ::FLAC__stream_encoder_get_max_residual_partition_order(encoder_);
324      }
325 
326      unsigned Stream::get_rice_parameter_search_dist() const
327      {
328         FLAC__ASSERT(is_valid());
329         return ::FLAC__stream_encoder_get_rice_parameter_search_dist(encoder_);
330      }
331 
332      FLAC__uint64 Stream::get_total_samples_estimate() const
333      {
334         FLAC__ASSERT(is_valid());
335         return ::FLAC__stream_encoder_get_total_samples_estimate(encoder_);
336      }
337 
338      ::FLAC__StreamEncoderInitStatus Stream::init()
339      {
340         FLAC__ASSERT(is_valid());
341         return ::FLAC__stream_encoder_init_stream(encoder_, write_callback_, seek_callback_, tell_callback_, metadata_callback_, /*client_data=*/(void*)this);
342      }
343 
344      ::FLAC__StreamEncoderInitStatus Stream::init_ogg()
345      {
346         FLAC__ASSERT(is_valid());
347         return ::FLAC__stream_encoder_init_ogg_stream(encoder_, read_callback_, write_callback_, seek_callback_, tell_callback_, metadata_callback_, /*client_data=*/(void*)this);
348      }
349 
350      bool Stream::finish()
351      {
352         FLAC__ASSERT(is_valid());
353         return (bool)::FLAC__stream_encoder_finish(encoder_);
354      }
355 
356      bool Stream::process(const FLAC__int32 * const buffer[], unsigned samples)
357      {
358         FLAC__ASSERT(is_valid());
359         return (bool)::FLAC__stream_encoder_process(encoder_, buffer, samples);
360      }
361 
362      bool Stream::process_interleaved(const FLAC__int32 buffer[], unsigned samples)
363      {
364         FLAC__ASSERT(is_valid());
365         return (bool)::FLAC__stream_encoder_process_interleaved(encoder_, buffer, samples);
366      }
367 
368      ::FLAC__StreamEncoderReadStatus Stream::read_callback(FLAC__byte buffer[], size_t *bytes)
369      {
370         (void)buffer, (void)bytes;
371         return ::FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED;
372      }
373 
374      ::FLAC__StreamEncoderSeekStatus Stream::seek_callback(FLAC__uint64 absolute_byte_offset)
375      {
376         (void)absolute_byte_offset;
377         return ::FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
378      }
379 
380      ::FLAC__StreamEncoderTellStatus Stream::tell_callback(FLAC__uint64 *absolute_byte_offset)
381      {
382         (void)absolute_byte_offset;
383         return ::FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
384      }
385 
386      void Stream::metadata_callback(const ::FLAC__StreamMetadata *metadata)
387      {
388         (void)metadata;
389      }
390 
391      ::FLAC__StreamEncoderReadStatus Stream::read_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
392      {
393         (void)encoder;
394         FLAC__ASSERT(0 != client_data);
395         Stream *instance = reinterpret_cast<Stream *>(client_data);
396         FLAC__ASSERT(0 != instance);
397         return instance->read_callback(buffer, bytes);
398      }
399 
400      ::FLAC__StreamEncoderWriteStatus Stream::write_callback_(const ::FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
401      {
402         (void)encoder;
403         FLAC__ASSERT(0 != client_data);
404         Stream *instance = reinterpret_cast<Stream *>(client_data);
405         FLAC__ASSERT(0 != instance);
406         return instance->write_callback(buffer, bytes, samples, current_frame);
407      }
408 
409      ::FLAC__StreamEncoderSeekStatus Stream::seek_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
410      {
411         (void)encoder;
412         FLAC__ASSERT(0 != client_data);
413         Stream *instance = reinterpret_cast<Stream *>(client_data);
414         FLAC__ASSERT(0 != instance);
415         return instance->seek_callback(absolute_byte_offset);
416      }
417 
418      ::FLAC__StreamEncoderTellStatus Stream::tell_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
419      {
420         (void)encoder;
421         FLAC__ASSERT(0 != client_data);
422         Stream *instance = reinterpret_cast<Stream *>(client_data);
423         FLAC__ASSERT(0 != instance);
424         return instance->tell_callback(absolute_byte_offset);
425      }
426 
427      void Stream::metadata_callback_(const ::FLAC__StreamEncoder *encoder, const ::FLAC__StreamMetadata *metadata, void *client_data)
428      {
429         (void)encoder;
430         FLAC__ASSERT(0 != client_data);
431         Stream *instance = reinterpret_cast<Stream *>(client_data);
432         FLAC__ASSERT(0 != instance);
433         instance->metadata_callback(metadata);
434      }
435 
436      // ------------------------------------------------------------
437      //
438      // File
439      //
440      // ------------------------------------------------------------
441 
442      File::File():
443         Stream()
444      { }
445 
446      File::~File()
447      {
448      }
449 
450      ::FLAC__StreamEncoderInitStatus File::init(FILE *file)
451      {
452         FLAC__ASSERT(is_valid());
453         return ::FLAC__stream_encoder_init_FILE(encoder_, file, progress_callback_, /*client_data=*/(void*)this);
454      }
455 
456      ::FLAC__StreamEncoderInitStatus File::init(const char *filename)
457      {
458         FLAC__ASSERT(is_valid());
459         return ::FLAC__stream_encoder_init_file(encoder_, filename, progress_callback_, /*client_data=*/(void*)this);
460      }
461 
462      ::FLAC__StreamEncoderInitStatus File::init(const std::string &filename)
463      {
464         return init(filename.c_str());
465      }
466 
467      ::FLAC__StreamEncoderInitStatus File::init_ogg(FILE *file)
468      {
469         FLAC__ASSERT(is_valid());
470         return ::FLAC__stream_encoder_init_ogg_FILE(encoder_, file, progress_callback_, /*client_data=*/(void*)this);
471      }
472 
473      ::FLAC__StreamEncoderInitStatus File::init_ogg(const char *filename)
474      {
475         FLAC__ASSERT(is_valid());
476         return ::FLAC__stream_encoder_init_ogg_file(encoder_, filename, progress_callback_, /*client_data=*/(void*)this);
477      }
478 
479      ::FLAC__StreamEncoderInitStatus File::init_ogg(const std::string &filename)
480      {
481         return init_ogg(filename.c_str());
482      }
483 
484      // This is a dummy to satisfy the pure virtual from Stream; the
485      // read callback will never be called since we are initializing
486      // with FLAC__stream_decoder_init_FILE() or
487      // FLAC__stream_decoder_init_file() and those supply the read
488      // callback internally.
489      ::FLAC__StreamEncoderWriteStatus File::write_callback(const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame)
490      {
491         (void)buffer, (void)bytes, (void)samples, (void)current_frame;
492         FLAC__ASSERT(false);
493         return ::FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR; // double protection
494      }
495 
496      void File::progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate)
497      {
498         (void)bytes_written, (void)samples_written, (void)frames_written, (void)total_frames_estimate;
499      }
500 
501      void File::progress_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data)
502      {
503         (void)encoder;
504         FLAC__ASSERT(0 != client_data);
505         File *instance = reinterpret_cast<File *>(client_data);
506         FLAC__ASSERT(0 != instance);
507         instance->progress_callback(bytes_written, samples_written, frames_written, total_frames_estimate);
508      }
509 
510   }
511}
src/lib/libflac/include/share/alloc.h
r0r14135
1/* alloc - Convenience routines for safely allocating memory
2 * Copyright (C) 2007  Josh Coalson
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
17 */
18
19#ifndef FLAC__SHARE__ALLOC_H
20#define FLAC__SHARE__ALLOC_H
21
22#if HAVE_CONFIG_H
23#  include <config.h>
24#endif
25
26/* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
27 * before #including this file,  otherwise SIZE_MAX might not be defined
28 */
29
30#ifndef SIZE_MAX
31#define SIZE_MAX (4294967295U)
32#endif
33
34#include <limits.h> /* for SIZE_MAX */
35#if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
36#include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
37#endif
38#include <stdlib.h> /* for size_t, malloc(), etc */
39
40#ifndef SIZE_MAX
41# ifndef SIZE_T_MAX
42#  ifdef _MSC_VER
43#   define SIZE_T_MAX UINT_MAX
44#  else
45#   error
46#  endif
47# endif
48# define SIZE_MAX SIZE_T_MAX
49#endif
50
51#ifndef FLaC__INLINE
52#define FLaC__INLINE
53#endif
54
55/* avoid malloc()ing 0 bytes, see:
56 * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
57*/
58static FLaC__INLINE void *safe_malloc_(size_t size)
59{
60   /* malloc(0) is undefined; FLAC src convention is to always allocate */
61   if(!size)
62      size++;
63   return malloc(size);
64}
65
66static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
67{
68   if(!nmemb || !size)
69      return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
70   return calloc(nmemb, size);
71}
72
73/*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
74
75static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
76{
77   size2 += size1;
78   if(size2 < size1)
79      return 0;
80   return safe_malloc_(size2);
81}
82
83static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
84{
85   size2 += size1;
86   if(size2 < size1)
87      return 0;
88   size3 += size2;
89   if(size3 < size2)
90      return 0;
91   return safe_malloc_(size3);
92}
93
94static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
95{
96   size2 += size1;
97   if(size2 < size1)
98      return 0;
99   size3 += size2;
100   if(size3 < size2)
101      return 0;
102   size4 += size3;
103   if(size4 < size3)
104      return 0;
105   return safe_malloc_(size4);
106}
107
108static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
109#if 0
110needs support for cases where sizeof(size_t) != 4
111{
112   /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
113   if(sizeof(size_t) == 4) {
114      if ((double)size1 * (double)size2 < 4294967296.0)
115         return malloc(size1*size2);
116   }
117   return 0;
118}
119#else
120/* better? */
121{
122   if(!size1 || !size2)
123      return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
124   if(size1 > SIZE_MAX / size2)
125      return 0;
126   return malloc(size1*size2);
127}
128#endif
129
130static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
131{
132   if(!size1 || !size2 || !size3)
133      return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
134   if(size1 > SIZE_MAX / size2)
135      return 0;
136   size1 *= size2;
137   if(size1 > SIZE_MAX / size3)
138      return 0;
139   return malloc(size1*size3);
140}
141
142/* size1*size2 + size3 */
143static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
144{
145   if(!size1 || !size2)
146      return safe_malloc_(size3);
147   if(size1 > SIZE_MAX / size2)
148      return 0;
149   return safe_malloc_add_2op_(size1*size2, size3);
150}
151
152/* size1 * (size2 + size3) */
153static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
154{
155   if(!size1 || (!size2 && !size3))
156      return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
157   size2 += size3;
158   if(size2 < size3)
159      return 0;
160   return safe_malloc_mul_2op_(size1, size2);
161}
162
163static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
164{
165   size2 += size1;
166   if(size2 < size1)
167      return 0;
168   return realloc(ptr, size2);
169}
170
171static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
172{
173   size2 += size1;
174   if(size2 < size1)
175      return 0;
176   size3 += size2;
177   if(size3 < size2)
178      return 0;
179   return realloc(ptr, size3);
180}
181
182static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
183{
184   size2 += size1;
185   if(size2 < size1)
186      return 0;
187   size3 += size2;
188   if(size3 < size2)
189      return 0;
190   size4 += size3;
191   if(size4 < size3)
192      return 0;
193   return realloc(ptr, size4);
194}
195
196static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
197{
198   if(!size1 || !size2)
199      return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
200   if(size1 > SIZE_MAX / size2)
201      return 0;
202   return realloc(ptr, size1*size2);
203}
204
205/* size1 * (size2 + size3) */
206static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
207{
208   if(!size1 || (!size2 && !size3))
209      return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
210   size2 += size3;
211   if(size2 < size3)
212      return 0;
213   return safe_realloc_mul_2op_(ptr, size1, size2);
214}
215
216#endif
src/lib/libflac/include/share/utf8.h
r0r14135
1#ifndef SHARE__UTF8_H
2#define SHARE__UTF8_H
3
4/*
5 * Convert a string between UTF-8 and the locale's charset.
6 * Invalid bytes are replaced by '#', and characters that are
7 * not available in the target encoding are replaced by '?'.
8 *
9 * If the locale's charset is not set explicitly then it is
10 * obtained using nl_langinfo(CODESET), where available, the
11 * environment variable CHARSET, or assumed to be US-ASCII.
12 *
13 * Return value of conversion functions:
14 *
15 *  -1 : memory allocation failed
16 *   0 : data was converted exactly
17 *   1 : valid data was converted approximately (using '?')
18 *   2 : input was invalid (but still converted, using '#')
19 *   3 : unknown encoding (but still converted, using '?')
20 */
21
22int utf8_encode(const char *from, char **to);
23int utf8_decode(const char *from, char **to);
24
25#endif
src/lib/libflac/include/flac/stream_encoder.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__STREAM_ENCODER_H
33#define FLAC__STREAM_ENCODER_H
34
35#include <stdio.h> /* for FILE */
36#include "export.h"
37#include "format.h"
38#include "stream_decoder.h"
39
40#ifdef __cplusplus
41extern "C" {
42#endif
43
44
45/** \file include/FLAC/stream_encoder.h
46 *
47 *  \brief
48 *  This module contains the functions which implement the stream
49 *  encoder.
50 *
51 *  See the detailed documentation in the
52 *  \link flac_stream_encoder stream encoder \endlink module.
53 */
54
55/** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
56 *  \ingroup flac
57 *
58 *  \brief
59 *  This module describes the encoder layers provided by libFLAC.
60 *
61 * The stream encoder can be used to encode complete streams either to the
62 * client via callbacks, or directly to a file, depending on how it is
63 * initialized.  When encoding via callbacks, the client provides a write
64 * callback which will be called whenever FLAC data is ready to be written.
65 * If the client also supplies a seek callback, the encoder will also
66 * automatically handle the writing back of metadata discovered while
67 * encoding, like stream info, seek points offsets, etc.  When encoding to
68 * a file, the client needs only supply a filename or open \c FILE* and an
69 * optional progress callback for periodic notification of progress; the
70 * write and seek callbacks are supplied internally.  For more info see the
71 * \link flac_stream_encoder stream encoder \endlink module.
72 */
73
74/** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
75 *  \ingroup flac_encoder
76 *
77 *  \brief
78 *  This module contains the functions which implement the stream
79 *  encoder.
80 *
81 * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
82 * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
83 *
84 * The basic usage of this encoder is as follows:
85 * - The program creates an instance of an encoder using
86 *   FLAC__stream_encoder_new().
87 * - The program overrides the default settings using
88 *   FLAC__stream_encoder_set_*() functions.  At a minimum, the following
89 *   functions should be called:
90 *   - FLAC__stream_encoder_set_channels()
91 *   - FLAC__stream_encoder_set_bits_per_sample()
92 *   - FLAC__stream_encoder_set_sample_rate()
93 *   - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
94 *   - FLAC__stream_encoder_set_total_samples_estimate() (if known)
95 * - If the application wants to control the compression level or set its own
96 *   metadata, then the following should also be called:
97 *   - FLAC__stream_encoder_set_compression_level()
98 *   - FLAC__stream_encoder_set_verify()
99 *   - FLAC__stream_encoder_set_metadata()
100 * - The rest of the set functions should only be called if the client needs
101 *   exact control over how the audio is compressed; thorough understanding
102 *   of the FLAC format is necessary to achieve good results.
103 * - The program initializes the instance to validate the settings and
104 *   prepare for encoding using
105 *   - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
106 *     or FLAC__stream_encoder_init_file() for native FLAC
107 *   - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
108 *     or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
109 * - The program calls FLAC__stream_encoder_process() or
110 *   FLAC__stream_encoder_process_interleaved() to encode data, which
111 *   subsequently calls the callbacks when there is encoder data ready
112 *   to be written.
113 * - The program finishes the encoding with FLAC__stream_encoder_finish(),
114 *   which causes the encoder to encode any data still in its input pipe,
115 *   update the metadata with the final encoding statistics if output
116 *   seeking is possible, and finally reset the encoder to the
117 *   uninitialized state.
118 * - The instance may be used again or deleted with
119 *   FLAC__stream_encoder_delete().
120 *
121 * In more detail, the stream encoder functions similarly to the
122 * \link flac_stream_decoder stream decoder \endlink, but has fewer
123 * callbacks and more options.  Typically the client will create a new
124 * instance by calling FLAC__stream_encoder_new(), then set the necessary
125 * parameters with FLAC__stream_encoder_set_*(), and initialize it by
126 * calling one of the FLAC__stream_encoder_init_*() functions.
127 *
128 * Unlike the decoders, the stream encoder has many options that can
129 * affect the speed and compression ratio.  When setting these parameters
130 * you should have some basic knowledge of the format (see the
131 * <A HREF="../documentation.html#format">user-level documentation</A>
132 * or the <A HREF="../format.html">formal description</A>).  The
133 * FLAC__stream_encoder_set_*() functions themselves do not validate the
134 * values as many are interdependent.  The FLAC__stream_encoder_init_*()
135 * functions will do this, so make sure to pay attention to the state
136 * returned by FLAC__stream_encoder_init_*() to make sure that it is
137 * FLAC__STREAM_ENCODER_INIT_STATUS_OK.  Any parameters that are not set
138 * before FLAC__stream_encoder_init_*() will take on the defaults from
139 * the constructor.
140 *
141 * There are three initialization functions for native FLAC, one for
142 * setting up the encoder to encode FLAC data to the client via
143 * callbacks, and two for encoding directly to a file.
144 *
145 * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
146 * You must also supply a write callback which will be called anytime
147 * there is raw encoded data to write.  If the client can seek the output
148 * it is best to also supply seek and tell callbacks, as this allows the
149 * encoder to go back after encoding is finished to write back
150 * information that was collected while encoding, like seek point offsets,
151 * frame sizes, etc.
152 *
153 * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
154 * or FLAC__stream_encoder_init_file().  Then you must only supply a
155 * filename or open \c FILE*; the encoder will handle all the callbacks
156 * internally.  You may also supply a progress callback for periodic
157 * notification of the encoding progress.
158 *
159 * There are three similarly-named init functions for encoding to Ogg
160 * FLAC streams.  Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
161 * library has been built with Ogg support.
162 *
163 * The call to FLAC__stream_encoder_init_*() currently will also immediately
164 * call the write callback several times, once with the \c fLaC signature,
165 * and once for each encoded metadata block.  Note that for Ogg FLAC
166 * encoding you will usually get at least twice the number of callbacks than
167 * with native FLAC, one for the Ogg page header and one for the page body.
168 *
169 * After initializing the instance, the client may feed audio data to the
170 * encoder in one of two ways:
171 *
172 * - Channel separate, through FLAC__stream_encoder_process() - The client
173 *   will pass an array of pointers to buffers, one for each channel, to
174 *   the encoder, each of the same length.  The samples need not be
175 *   block-aligned, but each channel should have the same number of samples.
176 * - Channel interleaved, through
177 *   FLAC__stream_encoder_process_interleaved() - The client will pass a single
178 *   pointer to data that is channel-interleaved (i.e. channel0_sample0,
179 *   channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
180 *   Again, the samples need not be block-aligned but they must be
181 *   sample-aligned, i.e. the first value should be channel0_sample0 and
182 *   the last value channelN_sampleM.
183 *
184 * Note that for either process call, each sample in the buffers should be a
185 * signed integer, right-justified to the resolution set by
186 * FLAC__stream_encoder_set_bits_per_sample().  For example, if the resolution
187 * is 16 bits per sample, the samples should all be in the range [-32768,32767].
188 *
189 * When the client is finished encoding data, it calls
190 * FLAC__stream_encoder_finish(), which causes the encoder to encode any
191 * data still in its input pipe, and call the metadata callback with the
192 * final encoding statistics.  Then the instance may be deleted with
193 * FLAC__stream_encoder_delete() or initialized again to encode another
194 * stream.
195 *
196 * For programs that write their own metadata, but that do not know the
197 * actual metadata until after encoding, it is advantageous to instruct
198 * the encoder to write a PADDING block of the correct size, so that
199 * instead of rewriting the whole stream after encoding, the program can
200 * just overwrite the PADDING block.  If only the maximum size of the
201 * metadata is known, the program can write a slightly larger padding
202 * block, then split it after encoding.
203 *
204 * Make sure you understand how lengths are calculated.  All FLAC metadata
205 * blocks have a 4 byte header which contains the type and length.  This
206 * length does not include the 4 bytes of the header.  See the format page
207 * for the specification of metadata blocks and their lengths.
208 *
209 * \note
210 * If you are writing the FLAC data to a file via callbacks, make sure it
211 * is open for update (e.g. mode "w+" for stdio streams).  This is because
212 * after the first encoding pass, the encoder will try to seek back to the
213 * beginning of the stream, to the STREAMINFO block, to write some data
214 * there.  (If using FLAC__stream_encoder_init*_file() or
215 * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
216 *
217 * \note
218 * The "set" functions may only be called when the encoder is in the
219 * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
220 * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
221 * before FLAC__stream_encoder_init_*().  If this is the case they will
222 * return \c true, otherwise \c false.
223 *
224 * \note
225 * FLAC__stream_encoder_finish() resets all settings to the constructor
226 * defaults.
227 *
228 * \{
229 */
230
231
232/** State values for a FLAC__StreamEncoder.
233 *
234 * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
235 *
236 * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
237 * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
238 * must be deleted with FLAC__stream_encoder_delete().
239 */
240typedef enum {
241
242   FLAC__STREAM_ENCODER_OK = 0,
243   /**< The encoder is in the normal OK state and samples can be processed. */
244
245   FLAC__STREAM_ENCODER_UNINITIALIZED,
246   /**< The encoder is in the uninitialized state; one of the
247    * FLAC__stream_encoder_init_*() functions must be called before samples
248    * can be processed.
249    */
250
251   FLAC__STREAM_ENCODER_OGG_ERROR,
252   /**< An error occurred in the underlying Ogg layer.  */
253
254   FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
255   /**< An error occurred in the underlying verify stream decoder;
256    * check FLAC__stream_encoder_get_verify_decoder_state().
257    */
258
259   FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
260   /**< The verify decoder detected a mismatch between the original
261    * audio signal and the decoded audio signal.
262    */
263
264   FLAC__STREAM_ENCODER_CLIENT_ERROR,
265   /**< One of the callbacks returned a fatal error. */
266
267   FLAC__STREAM_ENCODER_IO_ERROR,
268   /**< An I/O error occurred while opening/reading/writing a file.
269    * Check \c errno.
270    */
271
272   FLAC__STREAM_ENCODER_FRAMING_ERROR,
273   /**< An error occurred while writing the stream; usually, the
274    * write_callback returned an error.
275    */
276
277   FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
278   /**< Memory allocation failed. */
279
280} FLAC__StreamEncoderState;
281
282/** Maps a FLAC__StreamEncoderState to a C string.
283 *
284 *  Using a FLAC__StreamEncoderState as the index to this array
285 *  will give the string equivalent.  The contents should not be modified.
286 */
287extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
288
289
290/** Possible return values for the FLAC__stream_encoder_init_*() functions.
291 */
292typedef enum {
293
294   FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
295   /**< Initialization was successful. */
296
297   FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
298   /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
299
300   FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
301   /**< The library was not compiled with support for the given container
302    * format.
303    */
304
305   FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
306   /**< A required callback was not supplied. */
307
308   FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
309   /**< The encoder has an invalid setting for number of channels. */
310
311   FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
312   /**< The encoder has an invalid setting for bits-per-sample.
313    * FLAC supports 4-32 bps but the reference encoder currently supports
314    * only up to 24 bps.
315    */
316
317   FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
318   /**< The encoder has an invalid setting for the input sample rate. */
319
320   FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
321   /**< The encoder has an invalid setting for the block size. */
322
323   FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
324   /**< The encoder has an invalid setting for the maximum LPC order. */
325
326   FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
327   /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
328
329   FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
330   /**< The specified block size is less than the maximum LPC order. */
331
332   FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
333   /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
334
335   FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
336   /**< The metadata input to the encoder is invalid, in one of the following ways:
337    * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
338    * - One of the metadata blocks contains an undefined type
339    * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
340    * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
341    * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
342    */
343
344   FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
345   /**< FLAC__stream_encoder_init_*() was called when the encoder was
346    * already initialized, usually because
347    * FLAC__stream_encoder_finish() was not called.
348    */
349
350} FLAC__StreamEncoderInitStatus;
351
352/** Maps a FLAC__StreamEncoderInitStatus to a C string.
353 *
354 *  Using a FLAC__StreamEncoderInitStatus as the index to this array
355 *  will give the string equivalent.  The contents should not be modified.
356 */
357extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
358
359
360/** Return values for the FLAC__StreamEncoder read callback.
361 */
362typedef enum {
363
364   FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
365   /**< The read was OK and decoding can continue. */
366
367   FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
368   /**< The read was attempted at the end of the stream. */
369
370   FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
371   /**< An unrecoverable error occurred. */
372
373   FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
374   /**< Client does not support reading back from the output. */
375
376} FLAC__StreamEncoderReadStatus;
377
378/** Maps a FLAC__StreamEncoderReadStatus to a C string.
379 *
380 *  Using a FLAC__StreamEncoderReadStatus as the index to this array
381 *  will give the string equivalent.  The contents should not be modified.
382 */
383extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
384
385
386/** Return values for the FLAC__StreamEncoder write callback.
387 */
388typedef enum {
389
390   FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
391   /**< The write was OK and encoding can continue. */
392
393   FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
394   /**< An unrecoverable error occurred.  The encoder will return from the process call. */
395
396} FLAC__StreamEncoderWriteStatus;
397
398/** Maps a FLAC__StreamEncoderWriteStatus to a C string.
399 *
400 *  Using a FLAC__StreamEncoderWriteStatus as the index to this array
401 *  will give the string equivalent.  The contents should not be modified.
402 */
403extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
404
405
406/** Return values for the FLAC__StreamEncoder seek callback.
407 */
408typedef enum {
409
410   FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
411   /**< The seek was OK and encoding can continue. */
412
413   FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
414   /**< An unrecoverable error occurred. */
415
416   FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
417   /**< Client does not support seeking. */
418
419} FLAC__StreamEncoderSeekStatus;
420
421/** Maps a FLAC__StreamEncoderSeekStatus to a C string.
422 *
423 *  Using a FLAC__StreamEncoderSeekStatus as the index to this array
424 *  will give the string equivalent.  The contents should not be modified.
425 */
426extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
427
428
429/** Return values for the FLAC__StreamEncoder tell callback.
430 */
431typedef enum {
432
433   FLAC__STREAM_ENCODER_TELL_STATUS_OK,
434   /**< The tell was OK and encoding can continue. */
435
436   FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
437   /**< An unrecoverable error occurred. */
438
439   FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
440   /**< Client does not support seeking. */
441
442} FLAC__StreamEncoderTellStatus;
443
444/** Maps a FLAC__StreamEncoderTellStatus to a C string.
445 *
446 *  Using a FLAC__StreamEncoderTellStatus as the index to this array
447 *  will give the string equivalent.  The contents should not be modified.
448 */
449extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
450
451
452/***********************************************************************
453 *
454 * class FLAC__StreamEncoder
455 *
456 ***********************************************************************/
457
458struct FLAC__StreamEncoderProtected;
459struct FLAC__StreamEncoderPrivate;
460/** The opaque structure definition for the stream encoder type.
461 *  See the \link flac_stream_encoder stream encoder module \endlink
462 *  for a detailed description.
463 */
464typedef struct {
465   struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
466   struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
467} FLAC__StreamEncoder;
468
469/** Signature for the read callback.
470 *
471 *  A function pointer matching this signature must be passed to
472 *  FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
473 *  The supplied function will be called when the encoder needs to read back
474 *  encoded data.  This happens during the metadata callback, when the encoder
475 *  has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
476 *  while encoding.  The address of the buffer to be filled is supplied, along
477 *  with the number of bytes the buffer can hold.  The callback may choose to
478 *  supply less data and modify the byte count but must be careful not to
479 *  overflow the buffer.  The callback then returns a status code chosen from
480 *  FLAC__StreamEncoderReadStatus.
481 *
482 * Here is an example of a read callback for stdio streams:
483 * \code
484 * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
485 * {
486 *   FILE *file = ((MyClientData*)client_data)->file;
487 *   if(*bytes > 0) {
488 *     *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
489 *     if(ferror(file))
490 *       return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
491 *     else if(*bytes == 0)
492 *       return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
493 *     else
494 *       return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
495 *   }
496 *   else
497 *     return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
498 * }
499 * \endcode
500 *
501 * \note In general, FLAC__StreamEncoder functions which change the
502 * state should not be called on the \a encoder while in the callback.
503 *
504 * \param  encoder  The encoder instance calling the callback.
505 * \param  buffer   A pointer to a location for the callee to store
506 *                  data to be encoded.
507 * \param  bytes    A pointer to the size of the buffer.  On entry
508 *                  to the callback, it contains the maximum number
509 *                  of bytes that may be stored in \a buffer.  The
510 *                  callee must set it to the actual number of bytes
511 *                  stored (0 in case of error or end-of-stream) before
512 *                  returning.
513 * \param  client_data  The callee's client data set through
514 *                      FLAC__stream_encoder_set_client_data().
515 * \retval FLAC__StreamEncoderReadStatus
516 *    The callee's return status.
517 */
518typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
519
520/** Signature for the write callback.
521 *
522 *  A function pointer matching this signature must be passed to
523 *  FLAC__stream_encoder_init*_stream().  The supplied function will be called
524 *  by the encoder anytime there is raw encoded data ready to write.  It may
525 *  include metadata mixed with encoded audio frames and the data is not
526 *  guaranteed to be aligned on frame or metadata block boundaries.
527 *
528 *  The only duty of the callback is to write out the \a bytes worth of data
529 *  in \a buffer to the current position in the output stream.  The arguments
530 *  \a samples and \a current_frame are purely informational.  If \a samples
531 *  is greater than \c 0, then \a current_frame will hold the current frame
532 *  number that is being written; otherwise it indicates that the write
533 *  callback is being called to write metadata.
534 *
535 * \note
536 * Unlike when writing to native FLAC, when writing to Ogg FLAC the
537 * write callback will be called twice when writing each audio
538 * frame; once for the page header, and once for the page body.
539 * When writing the page header, the \a samples argument to the
540 * write callback will be \c 0.
541 *
542 * \note In general, FLAC__StreamEncoder functions which change the
543 * state should not be called on the \a encoder while in the callback.
544 *
545 * \param  encoder  The encoder instance calling the callback.
546 * \param  buffer   An array of encoded data of length \a bytes.
547 * \param  bytes    The byte length of \a buffer.
548 * \param  samples  The number of samples encoded by \a buffer.
549 *                  \c 0 has a special meaning; see above.
550 * \param  current_frame  The number of the current frame being encoded.
551 * \param  client_data  The callee's client data set through
552 *                      FLAC__stream_encoder_init_*().
553 * \retval FLAC__StreamEncoderWriteStatus
554 *    The callee's return status.
555 */
556typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
557
558/** Signature for the seek callback.
559 *
560 *  A function pointer matching this signature may be passed to
561 *  FLAC__stream_encoder_init*_stream().  The supplied function will be called
562 *  when the encoder needs to seek the output stream.  The encoder will pass
563 *  the absolute byte offset to seek to, 0 meaning the beginning of the stream.
564 *
565 * Here is an example of a seek callback for stdio streams:
566 * \code
567 * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
568 * {
569 *   FILE *file = ((MyClientData*)client_data)->file;
570 *   if(file == stdin)
571 *     return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
572 *   else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
573 *     return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
574 *   else
575 *     return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
576 * }
577 * \endcode
578 *
579 * \note In general, FLAC__StreamEncoder functions which change the
580 * state should not be called on the \a encoder while in the callback.
581 *
582 * \param  encoder  The encoder instance calling the callback.
583 * \param  absolute_byte_offset  The offset from the beginning of the stream
584 *                               to seek to.
585 * \param  client_data  The callee's client data set through
586 *                      FLAC__stream_encoder_init_*().
587 * \retval FLAC__StreamEncoderSeekStatus
588 *    The callee's return status.
589 */
590typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
591
592/** Signature for the tell callback.
593 *
594 *  A function pointer matching this signature may be passed to
595 *  FLAC__stream_encoder_init*_stream().  The supplied function will be called
596 *  when the encoder needs to know the current position of the output stream.
597 *
598 * \warning
599 * The callback must return the true current byte offset of the output to
600 * which the encoder is writing.  If you are buffering the output, make
601 * sure and take this into account.  If you are writing directly to a
602 * FILE* from your write callback, ftell() is sufficient.  If you are
603 * writing directly to a file descriptor from your write callback, you
604 * can use lseek(fd, SEEK_CUR, 0).  The encoder may later seek back to
605 * these points to rewrite metadata after encoding.
606 *
607 * Here is an example of a tell callback for stdio streams:
608 * \code
609 * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
610 * {
611 *   FILE *file = ((MyClientData*)client_data)->file;
612 *   off_t pos;
613 *   if(file == stdin)
614 *     return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
615 *   else if((pos = ftello(file)) < 0)
616 *     return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
617 *   else {
618 *     *absolute_byte_offset = (FLAC__uint64)pos;
619 *     return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
620 *   }
621 * }
622 * \endcode
623 *
624 * \note In general, FLAC__StreamEncoder functions which change the
625 * state should not be called on the \a encoder while in the callback.
626 *
627 * \param  encoder  The encoder instance calling the callback.
628 * \param  absolute_byte_offset  The address at which to store the current
629 *                               position of the output.
630 * \param  client_data  The callee's client data set through
631 *                      FLAC__stream_encoder_init_*().
632 * \retval FLAC__StreamEncoderTellStatus
633 *    The callee's return status.
634 */
635typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
636
637/** Signature for the metadata callback.
638 *
639 *  A function pointer matching this signature may be passed to
640 *  FLAC__stream_encoder_init*_stream().  The supplied function will be called
641 *  once at the end of encoding with the populated STREAMINFO structure.  This
642 *  is so the client can seek back to the beginning of the file and write the
643 *  STREAMINFO block with the correct statistics after encoding (like
644 *  minimum/maximum frame size and total samples).
645 *
646 * \note In general, FLAC__StreamEncoder functions which change the
647 * state should not be called on the \a encoder while in the callback.
648 *
649 * \param  encoder      The encoder instance calling the callback.
650 * \param  metadata     The final populated STREAMINFO block.
651 * \param  client_data  The callee's client data set through
652 *                      FLAC__stream_encoder_init_*().
653 */
654typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
655
656/** Signature for the progress callback.
657 *
658 *  A function pointer matching this signature may be passed to
659 *  FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
660 *  The supplied function will be called when the encoder has finished
661 *  writing a frame.  The \c total_frames_estimate argument to the
662 *  callback will be based on the value from
663 *  FLAC__stream_encoder_set_total_samples_estimate().
664 *
665 * \note In general, FLAC__StreamEncoder functions which change the
666 * state should not be called on the \a encoder while in the callback.
667 *
668 * \param  encoder          The encoder instance calling the callback.
669 * \param  bytes_written    Bytes written so far.
670 * \param  samples_written  Samples written so far.
671 * \param  frames_written   Frames written so far.
672 * \param  total_frames_estimate  The estimate of the total number of
673 *                                frames to be written.
674 * \param  client_data      The callee's client data set through
675 *                          FLAC__stream_encoder_init_*().
676 */
677typedef 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);
678
679
680/***********************************************************************
681 *
682 * Class constructor/destructor
683 *
684 ***********************************************************************/
685
686/** Create a new stream encoder instance.  The instance is created with
687 *  default settings; see the individual FLAC__stream_encoder_set_*()
688 *  functions for each setting's default.
689 *
690 * \retval FLAC__StreamEncoder*
691 *    \c NULL if there was an error allocating memory, else the new instance.
692 */
693FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
694
695/** Free an encoder instance.  Deletes the object pointed to by \a encoder.
696 *
697 * \param encoder  A pointer to an existing encoder.
698 * \assert
699 *    \code encoder != NULL \endcode
700 */
701FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
702
703
704/***********************************************************************
705 *
706 * Public class method prototypes
707 *
708 ***********************************************************************/
709
710/** Set the serial number for the FLAC stream to use in the Ogg container.
711 *
712 * \note
713 * This does not need to be set for native FLAC encoding.
714 *
715 * \note
716 * It is recommended to set a serial number explicitly as the default of '0'
717 * may collide with other streams.
718 *
719 * \default \c 0
720 * \param  encoder        An encoder instance to set.
721 * \param  serial_number  See above.
722 * \assert
723 *    \code encoder != NULL \endcode
724 * \retval FLAC__bool
725 *    \c false if the encoder is already initialized, else \c true.
726 */
727FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
728
729/** Set the "verify" flag.  If \c true, the encoder will verify it's own
730 *  encoded output by feeding it through an internal decoder and comparing
731 *  the original signal against the decoded signal.  If a mismatch occurs,
732 *  the process call will return \c false.  Note that this will slow the
733 *  encoding process by the extra time required for decoding and comparison.
734 *
735 * \default \c false
736 * \param  encoder  An encoder instance to set.
737 * \param  value    Flag value (see above).
738 * \assert
739 *    \code encoder != NULL \endcode
740 * \retval FLAC__bool
741 *    \c false if the encoder is already initialized, else \c true.
742 */
743FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
744
745/** Set the <A HREF="../format.html#subset">Subset</A> flag.  If \c true,
746 *  the encoder will comply with the Subset and will check the
747 *  settings during FLAC__stream_encoder_init_*() to see if all settings
748 *  comply.  If \c false, the settings may take advantage of the full
749 *  range that the format allows.
750 *
751 *  Make sure you know what it entails before setting this to \c false.
752 *
753 * \default \c true
754 * \param  encoder  An encoder instance to set.
755 * \param  value    Flag value (see above).
756 * \assert
757 *    \code encoder != NULL \endcode
758 * \retval FLAC__bool
759 *    \c false if the encoder is already initialized, else \c true.
760 */
761FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
762
763/** Set the number of channels to be encoded.
764 *
765 * \default \c 2
766 * \param  encoder  An encoder instance to set.
767 * \param  value    See above.
768 * \assert
769 *    \code encoder != NULL \endcode
770 * \retval FLAC__bool
771 *    \c false if the encoder is already initialized, else \c true.
772 */
773FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
774
775/** Set the sample resolution of the input to be encoded.
776 *
777 * \warning
778 * Do not feed the encoder data that is wider than the value you
779 * set here or you will generate an invalid stream.
780 *
781 * \default \c 16
782 * \param  encoder  An encoder instance to set.
783 * \param  value    See above.
784 * \assert
785 *    \code encoder != NULL \endcode
786 * \retval FLAC__bool
787 *    \c false if the encoder is already initialized, else \c true.
788 */
789FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
790
791/** Set the sample rate (in Hz) of the input to be encoded.
792 *
793 * \default \c 44100
794 * \param  encoder  An encoder instance to set.
795 * \param  value    See above.
796 * \assert
797 *    \code encoder != NULL \endcode
798 * \retval FLAC__bool
799 *    \c false if the encoder is already initialized, else \c true.
800 */
801FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
802
803/** Set the compression level
804 *
805 * The compression level is roughly proportional to the amount of effort
806 * the encoder expends to compress the file.  A higher level usually
807 * means more computation but higher compression.  The default level is
808 * suitable for most applications.
809 *
810 * Currently the levels range from \c 0 (fastest, least compression) to
811 * \c 8 (slowest, most compression).  A value larger than \c 8 will be
812 * treated as \c 8.
813 *
814 * This function automatically calls the following other \c _set_
815 * functions with appropriate values, so the client does not need to
816 * unless it specifically wants to override them:
817 * - FLAC__stream_encoder_set_do_mid_side_stereo()
818 * - FLAC__stream_encoder_set_loose_mid_side_stereo()
819 * - FLAC__stream_encoder_set_apodization()
820 * - FLAC__stream_encoder_set_max_lpc_order()
821 * - FLAC__stream_encoder_set_qlp_coeff_precision()
822 * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
823 * - FLAC__stream_encoder_set_do_escape_coding()
824 * - FLAC__stream_encoder_set_do_exhaustive_model_search()
825 * - FLAC__stream_encoder_set_min_residual_partition_order()
826 * - FLAC__stream_encoder_set_max_residual_partition_order()
827 * - FLAC__stream_encoder_set_rice_parameter_search_dist()
828 *
829 * The actual values set for each level are:
830 * <table>
831 * <tr>
832 *  <td><b>level</b><td>
833 *  <td>do mid-side stereo<td>
834 *  <td>loose mid-side stereo<td>
835 *  <td>apodization<td>
836 *  <td>max lpc order<td>
837 *  <td>qlp coeff precision<td>
838 *  <td>qlp coeff prec search<td>
839 *  <td>escape coding<td>
840 *  <td>exhaustive model search<td>
841 *  <td>min residual partition order<td>
842 *  <td>max residual partition order<td>
843 *  <td>rice parameter search dist<td>
844 * </tr>
845 * <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>
846 * <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>
847 * <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>
848 * <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>
849 * <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>
850 * <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>
851 * <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>
852 * <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>
853 * <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>
854 * </table>
855 *
856 * \default \c 5
857 * \param  encoder  An encoder instance to set.
858 * \param  value    See above.
859 * \assert
860 *    \code encoder != NULL \endcode
861 * \retval FLAC__bool
862 *    \c false if the encoder is already initialized, else \c true.
863 */
864FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
865
866/** Set the blocksize to use while encoding.
867 *
868 * The number of samples to use per frame.  Use \c 0 to let the encoder
869 * estimate a blocksize; this is usually best.
870 *
871 * \default \c 0
872 * \param  encoder  An encoder instance to set.
873 * \param  value    See above.
874 * \assert
875 *    \code encoder != NULL \endcode
876 * \retval FLAC__bool
877 *    \c false if the encoder is already initialized, else \c true.
878 */
879FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
880
881/** Set to \c true to enable mid-side encoding on stereo input.  The
882 *  number of channels must be 2 for this to have any effect.  Set to
883 *  \c false to use only independent channel coding.
884 *
885 * \default \c false
886 * \param  encoder  An encoder instance to set.
887 * \param  value    Flag value (see above).
888 * \assert
889 *    \code encoder != NULL \endcode
890 * \retval FLAC__bool
891 *    \c false if the encoder is already initialized, else \c true.
892 */
893FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
894
895/** Set to \c true to enable adaptive switching between mid-side and
896 *  left-right encoding on stereo input.  Set to \c false to use
897 *  exhaustive searching.  Setting this to \c true requires
898 *  FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
899 *  \c true in order to have any effect.
900 *
901 * \default \c false
902 * \param  encoder  An encoder instance to set.
903 * \param  value    Flag value (see above).
904 * \assert
905 *    \code encoder != NULL \endcode
906 * \retval FLAC__bool
907 *    \c false if the encoder is already initialized, else \c true.
908 */
909FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
910
911/** Sets the apodization function(s) the encoder will use when windowing
912 *  audio data for LPC analysis.
913 *
914 * The \a specification is a plain ASCII string which specifies exactly
915 * which functions to use.  There may be more than one (up to 32),
916 * separated by \c ';' characters.  Some functions take one or more
917 * comma-separated arguments in parentheses.
918 *
919 * The available functions are \c bartlett, \c bartlett_hann,
920 * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
921 * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
922 * \c rectangle, \c triangle, \c tukey(P), \c welch.
923 *
924 * For \c gauss(STDDEV), STDDEV specifies the standard deviation
925 * (0<STDDEV<=0.5).
926 *
927 * For \c tukey(P), P specifies the fraction of the window that is
928 * tapered (0<=P<=1).  P=0 corresponds to \c rectangle and P=1
929 * corresponds to \c hann.
930 *
931 * Example specifications are \c "blackman" or
932 * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
933 *
934 * Any function that is specified erroneously is silently dropped.  Up
935 * to 32 functions are kept, the rest are dropped.  If the specification
936 * is empty the encoder defaults to \c "tukey(0.5)".
937 *
938 * When more than one function is specified, then for every subframe the
939 * encoder will try each of them separately and choose the window that
940 * results in the smallest compressed subframe.
941 *
942 * Note that each function specified causes the encoder to occupy a
943 * floating point array in which to store the window.
944 *
945 * \default \c "tukey(0.5)"
946 * \param  encoder        An encoder instance to set.
947 * \param  specification  See above.
948 * \assert
949 *    \code encoder != NULL \endcode
950 *    \code specification != NULL \endcode
951 * \retval FLAC__bool
952 *    \c false if the encoder is already initialized, else \c true.
953 */
954FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
955
956/** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
957 *
958 * \default \c 0
959 * \param  encoder  An encoder instance to set.
960 * \param  value    See above.
961 * \assert
962 *    \code encoder != NULL \endcode
963 * \retval FLAC__bool
964 *    \c false if the encoder is already initialized, else \c true.
965 */
966FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
967
968/** Set the precision, in bits, of the quantized linear predictor
969 *  coefficients, or \c 0 to let the encoder select it based on the
970 *  blocksize.
971 *
972 * \note
973 * In the current implementation, qlp_coeff_precision + bits_per_sample must
974 * be less than 32.
975 *
976 * \default \c 0
977 * \param  encoder  An encoder instance to set.
978 * \param  value    See above.
979 * \assert
980 *    \code encoder != NULL \endcode
981 * \retval FLAC__bool
982 *    \c false if the encoder is already initialized, else \c true.
983 */
984FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
985
986/** Set to \c false to use only the specified quantized linear predictor
987 *  coefficient precision, or \c true to search neighboring precision
988 *  values and use the best one.
989 *
990 * \default \c false
991 * \param  encoder  An encoder instance to set.
992 * \param  value    See above.
993 * \assert
994 *    \code encoder != NULL \endcode
995 * \retval FLAC__bool
996 *    \c false if the encoder is already initialized, else \c true.
997 */
998FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
999
1000/** Deprecated.  Setting this value has no effect.
1001 *
1002 * \default \c false
1003 * \param  encoder  An encoder instance to set.
1004 * \param  value    See above.
1005 * \assert
1006 *    \code encoder != NULL \endcode
1007 * \retval FLAC__bool
1008 *    \c false if the encoder is already initialized, else \c true.
1009 */
1010FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
1011
1012/** Set to \c false to let the encoder estimate the best model order
1013 *  based on the residual signal energy, or \c true to force the
1014 *  encoder to evaluate all order models and select the best.
1015 *
1016 * \default \c false
1017 * \param  encoder  An encoder instance to set.
1018 * \param  value    See above.
1019 * \assert
1020 *    \code encoder != NULL \endcode
1021 * \retval FLAC__bool
1022 *    \c false if the encoder is already initialized, else \c true.
1023 */
1024FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
1025
1026/** Set the minimum partition order to search when coding the residual.
1027 *  This is used in tandem with
1028 *  FLAC__stream_encoder_set_max_residual_partition_order().
1029 *
1030 *  The partition order determines the context size in the residual.
1031 *  The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
1032 *
1033 *  Set both min and max values to \c 0 to force a single context,
1034 *  whose Rice parameter is based on the residual signal variance.
1035 *  Otherwise, set a min and max order, and the encoder will search
1036 *  all orders, using the mean of each context for its Rice parameter,
1037 *  and use the best.
1038 *
1039 * \default \c 0
1040 * \param  encoder  An encoder instance to set.
1041 * \param  value    See above.
1042 * \assert
1043 *    \code encoder != NULL \endcode
1044 * \retval FLAC__bool
1045 *    \c false if the encoder is already initialized, else \c true.
1046 */
1047FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
1048
1049/** Set the maximum partition order to search when coding the residual.
1050 *  This is used in tandem with
1051 *  FLAC__stream_encoder_set_min_residual_partition_order().
1052 *
1053 *  The partition order determines the context size in the residual.
1054 *  The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
1055 *
1056 *  Set both min and max values to \c 0 to force a single context,
1057 *  whose Rice parameter is based on the residual signal variance.
1058 *  Otherwise, set a min and max order, and the encoder will search
1059 *  all orders, using the mean of each context for its Rice parameter,
1060 *  and use the best.
1061 *
1062 * \default \c 0
1063 * \param  encoder  An encoder instance to set.
1064 * \param  value    See above.
1065 * \assert
1066 *    \code encoder != NULL \endcode
1067 * \retval FLAC__bool
1068 *    \c false if the encoder is already initialized, else \c true.
1069 */
1070FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
1071
1072/** Deprecated.  Setting this value has no effect.
1073 *
1074 * \default \c 0
1075 * \param  encoder  An encoder instance to set.
1076 * \param  value    See above.
1077 * \assert
1078 *    \code encoder != NULL \endcode
1079 * \retval FLAC__bool
1080 *    \c false if the encoder is already initialized, else \c true.
1081 */
1082FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
1083
1084/** Set an estimate of the total samples that will be encoded.
1085 *  This is merely an estimate and may be set to \c 0 if unknown.
1086 *  This value will be written to the STREAMINFO block before encoding,
1087 *  and can remove the need for the caller to rewrite the value later
1088 *  if the value is known before encoding.
1089 *
1090 * \default \c 0
1091 * \param  encoder  An encoder instance to set.
1092 * \param  value    See above.
1093 * \assert
1094 *    \code encoder != NULL \endcode
1095 * \retval FLAC__bool
1096 *    \c false if the encoder is already initialized, else \c true.
1097 */
1098FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
1099
1100/** Set the metadata blocks to be emitted to the stream before encoding.
1101 *  A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
1102 *  array of pointers to metadata blocks.  The array is non-const since
1103 *  the encoder may need to change the \a is_last flag inside them, and
1104 *  in some cases update seek point offsets.  Otherwise, the encoder will
1105 *  not modify or free the blocks.  It is up to the caller to free the
1106 *  metadata blocks after encoding finishes.
1107 *
1108 * \note
1109 * The encoder stores only copies of the pointers in the \a metadata array;
1110 * the metadata blocks themselves must survive at least until after
1111 * FLAC__stream_encoder_finish() returns.  Do not free the blocks until then.
1112 *
1113 * \note
1114 * The STREAMINFO block is always written and no STREAMINFO block may
1115 * occur in the supplied array.
1116 *
1117 * \note
1118 * By default the encoder does not create a SEEKTABLE.  If one is supplied
1119 * in the \a metadata array, but the client has specified that it does not
1120 * support seeking, then the SEEKTABLE will be written verbatim.  However
1121 * by itself this is not very useful as the client will not know the stream
1122 * offsets for the seekpoints ahead of time.  In order to get a proper
1123 * seektable the client must support seeking.  See next note.
1124 *
1125 * \note
1126 * SEEKTABLE blocks are handled specially.  Since you will not know
1127 * the values for the seek point stream offsets, you should pass in
1128 * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
1129 * required sample numbers (or placeholder points), with \c 0 for the
1130 * \a frame_samples and \a stream_offset fields for each point.  If the
1131 * client has specified that it supports seeking by providing a seek
1132 * callback to FLAC__stream_encoder_init_stream() or both seek AND read
1133 * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
1134 * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
1135 * then while it is encoding the encoder will fill the stream offsets in
1136 * for you and when encoding is finished, it will seek back and write the
1137 * real values into the SEEKTABLE block in the stream.  There are helper
1138 * routines for manipulating seektable template blocks; see metadata.h:
1139 * FLAC__metadata_object_seektable_template_*().  If the client does
1140 * not support seeking, the SEEKTABLE will have inaccurate offsets which
1141 * will slow down or remove the ability to seek in the FLAC stream.
1142 *
1143 * \note
1144 * The encoder instance \b will modify the first \c SEEKTABLE block
1145 * as it transforms the template to a valid seektable while encoding,
1146 * but it is still up to the caller to free all metadata blocks after
1147 * encoding.
1148 *
1149 * \note
1150 * A VORBIS_COMMENT block may be supplied.  The vendor string in it
1151 * will be ignored.  libFLAC will use it's own vendor string. libFLAC
1152 * will not modify the passed-in VORBIS_COMMENT's vendor string, it
1153 * will simply write it's own into the stream.  If no VORBIS_COMMENT
1154 * block is present in the \a metadata array, libFLAC will write an
1155 * empty one, containing only the vendor string.
1156 *
1157 * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
1158 * the second metadata block of the stream.  The encoder already supplies
1159 * the STREAMINFO block automatically.  If \a metadata does not contain a
1160 * VORBIS_COMMENT block, the encoder will supply that too.  Otherwise, if
1161 * \a metadata does contain a VORBIS_COMMENT block and it is not the
1162 * first, the init function will reorder \a metadata by moving the
1163 * VORBIS_COMMENT block to the front; the relative ordering of the other
1164 * blocks will remain as they were.
1165 *
1166 * \note The Ogg FLAC mapping limits the number of metadata blocks per
1167 * stream to \c 65535.  If \a num_blocks exceeds this the function will
1168 * return \c false.
1169 *
1170 * \default \c NULL, 0
1171 * \param  encoder     An encoder instance to set.
1172 * \param  metadata    See above.
1173 * \param  num_blocks  See above.
1174 * \assert
1175 *    \code encoder != NULL \endcode
1176 * \retval FLAC__bool
1177 *    \c false if the encoder is already initialized, else \c true.
1178 *    \c false if the encoder is already initialized, or if
1179 *    \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
1180 */
1181FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
1182
1183/** Get the current encoder state.
1184 *
1185 * \param  encoder  An encoder instance to query.
1186 * \assert
1187 *    \code encoder != NULL \endcode
1188 * \retval FLAC__StreamEncoderState
1189 *    The current encoder state.
1190 */
1191FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
1192
1193/** Get the state of the verify stream decoder.
1194 *  Useful when the stream encoder state is
1195 *  \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
1196 *
1197 * \param  encoder  An encoder instance to query.
1198 * \assert
1199 *    \code encoder != NULL \endcode
1200 * \retval FLAC__StreamDecoderState
1201 *    The verify stream decoder state.
1202 */
1203FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
1204
1205/** Get the current encoder state as a C string.
1206 *  This version automatically resolves
1207 *  \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
1208 *  verify decoder's state.
1209 *
1210 * \param  encoder  A encoder instance to query.
1211 * \assert
1212 *    \code encoder != NULL \endcode
1213 * \retval const char *
1214 *    The encoder state as a C string.  Do not modify the contents.
1215 */
1216FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
1217
1218/** Get relevant values about the nature of a verify decoder error.
1219 *  Useful when the stream encoder state is
1220 *  \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.  The arguments should
1221 *  be addresses in which the stats will be returned, or NULL if value
1222 *  is not desired.
1223 *
1224 * \param  encoder  An encoder instance to query.
1225 * \param  absolute_sample  The absolute sample number of the mismatch.
1226 * \param  frame_number  The number of the frame in which the mismatch occurred.
1227 * \param  channel       The channel in which the mismatch occurred.
1228 * \param  sample        The number of the sample (relative to the frame) in
1229 *                       which the mismatch occurred.
1230 * \param  expected      The expected value for the sample in question.
1231 * \param  got           The actual value returned by the decoder.
1232 * \assert
1233 *    \code encoder != NULL \endcode
1234 */
1235FLAC_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);
1236
1237/** Get the "verify" flag.
1238 *
1239 * \param  encoder  An encoder instance to query.
1240 * \assert
1241 *    \code encoder != NULL \endcode
1242 * \retval FLAC__bool
1243 *    See FLAC__stream_encoder_set_verify().
1244 */
1245FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
1246
1247/** Get the <A HREF="../format.html#subset>Subset</A> flag.
1248 *
1249 * \param  encoder  An encoder instance to query.
1250 * \assert
1251 *    \code encoder != NULL \endcode
1252 * \retval FLAC__bool
1253 *    See FLAC__stream_encoder_set_streamable_subset().
1254 */
1255FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
1256
1257/** Get the number of input channels being processed.
1258 *
1259 * \param  encoder  An encoder instance to query.
1260 * \assert
1261 *    \code encoder != NULL \endcode
1262 * \retval unsigned
1263 *    See FLAC__stream_encoder_set_channels().
1264 */
1265FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
1266
1267/** Get the input sample resolution setting.
1268 *
1269 * \param  encoder  An encoder instance to query.
1270 * \assert
1271 *    \code encoder != NULL \endcode
1272 * \retval unsigned
1273 *    See FLAC__stream_encoder_set_bits_per_sample().
1274 */
1275FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
1276
1277/** Get the input sample rate setting.
1278 *
1279 * \param  encoder  An encoder instance to query.
1280 * \assert
1281 *    \code encoder != NULL \endcode
1282 * \retval unsigned
1283 *    See FLAC__stream_encoder_set_sample_rate().
1284 */
1285FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
1286
1287/** Get the blocksize setting.
1288 *
1289 * \param  encoder  An encoder instance to query.
1290 * \assert
1291 *    \code encoder != NULL \endcode
1292 * \retval unsigned
1293 *    See FLAC__stream_encoder_set_blocksize().
1294 */
1295FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
1296
1297/** Get the "mid/side stereo coding" flag.
1298 *
1299 * \param  encoder  An encoder instance to query.
1300 * \assert
1301 *    \code encoder != NULL \endcode
1302 * \retval FLAC__bool
1303 *    See FLAC__stream_encoder_get_do_mid_side_stereo().
1304 */
1305FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
1306
1307/** Get the "adaptive mid/side switching" flag.
1308 *
1309 * \param  encoder  An encoder instance to query.
1310 * \assert
1311 *    \code encoder != NULL \endcode
1312 * \retval FLAC__bool
1313 *    See FLAC__stream_encoder_set_loose_mid_side_stereo().
1314 */
1315FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
1316
1317/** Get the maximum LPC order setting.
1318 *
1319 * \param  encoder  An encoder instance to query.
1320 * \assert
1321 *    \code encoder != NULL \endcode
1322 * \retval unsigned
1323 *    See FLAC__stream_encoder_set_max_lpc_order().
1324 */
1325FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
1326
1327/** Get the quantized linear predictor coefficient precision setting.
1328 *
1329 * \param  encoder  An encoder instance to query.
1330 * \assert
1331 *    \code encoder != NULL \endcode
1332 * \retval unsigned
1333 *    See FLAC__stream_encoder_set_qlp_coeff_precision().
1334 */
1335FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
1336
1337/** Get the qlp coefficient precision search flag.
1338 *
1339 * \param  encoder  An encoder instance to query.
1340 * \assert
1341 *    \code encoder != NULL \endcode
1342 * \retval FLAC__bool
1343 *    See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
1344 */
1345FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
1346
1347/** Get the "escape coding" flag.
1348 *
1349 * \param  encoder  An encoder instance to query.
1350 * \assert
1351 *    \code encoder != NULL \endcode
1352 * \retval FLAC__bool
1353 *    See FLAC__stream_encoder_set_do_escape_coding().
1354 */
1355FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
1356
1357/** Get the exhaustive model search flag.
1358 *
1359 * \param  encoder  An encoder instance to query.
1360 * \assert
1361 *    \code encoder != NULL \endcode
1362 * \retval FLAC__bool
1363 *    See FLAC__stream_encoder_set_do_exhaustive_model_search().
1364 */
1365FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
1366
1367/** Get the minimum residual partition order setting.
1368 *
1369 * \param  encoder  An encoder instance to query.
1370 * \assert
1371 *    \code encoder != NULL \endcode
1372 * \retval unsigned
1373 *    See FLAC__stream_encoder_set_min_residual_partition_order().
1374 */
1375FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
1376
1377/** Get maximum residual partition order setting.
1378 *
1379 * \param  encoder  An encoder instance to query.
1380 * \assert
1381 *    \code encoder != NULL \endcode
1382 * \retval unsigned
1383 *    See FLAC__stream_encoder_set_max_residual_partition_order().
1384 */
1385FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
1386
1387/** Get the Rice parameter search distance setting.
1388 *
1389 * \param  encoder  An encoder instance to query.
1390 * \assert
1391 *    \code encoder != NULL \endcode
1392 * \retval unsigned
1393 *    See FLAC__stream_encoder_set_rice_parameter_search_dist().
1394 */
1395FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
1396
1397/** Get the previously set estimate of the total samples to be encoded.
1398 *  The encoder merely mimics back the value given to
1399 *  FLAC__stream_encoder_set_total_samples_estimate() since it has no
1400 *  other way of knowing how many samples the client will encode.
1401 *
1402 * \param  encoder  An encoder instance to set.
1403 * \assert
1404 *    \code encoder != NULL \endcode
1405 * \retval FLAC__uint64
1406 *    See FLAC__stream_encoder_get_total_samples_estimate().
1407 */
1408FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
1409
1410/** Initialize the encoder instance to encode native FLAC streams.
1411 *
1412 *  This flavor of initialization sets up the encoder to encode to a
1413 *  native FLAC stream. I/O is performed via callbacks to the client.
1414 *  For encoding to a plain file via filename or open \c FILE*,
1415 *  FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
1416 *  provide a simpler interface.
1417 *
1418 *  This function should be called after FLAC__stream_encoder_new() and
1419 *  FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
1420 *  or FLAC__stream_encoder_process_interleaved().
1421 *  initialization succeeded.
1422 *
1423 *  The call to FLAC__stream_encoder_init_stream() currently will also
1424 *  immediately call the write callback several times, once with the \c fLaC
1425 *  signature, and once for each encoded metadata block.
1426 *
1427 * \param  encoder            An uninitialized encoder instance.
1428 * \param  write_callback     See FLAC__StreamEncoderWriteCallback.  This
1429 *                            pointer must not be \c NULL.
1430 * \param  seek_callback      See FLAC__StreamEncoderSeekCallback.  This
1431 *                            pointer may be \c NULL if seeking is not
1432 *                            supported.  The encoder uses seeking to go back
1433 *                            and write some some stream statistics to the
1434 *                            STREAMINFO block; this is recommended but not
1435 *                            necessary to create a valid FLAC stream.  If
1436 *                            \a seek_callback is not \c NULL then a
1437 *                            \a tell_callback must also be supplied.
1438 *                            Alternatively, a dummy seek callback that just
1439 *                            returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
1440 *                            may also be supplied, all though this is slightly
1441 *                            less efficient for the encoder.
1442 * \param  tell_callback      See FLAC__StreamEncoderTellCallback.  This
1443 *                            pointer may be \c NULL if seeking is not
1444 *                            supported.  If \a seek_callback is \c NULL then
1445 *                            this argument will be ignored.  If
1446 *                            \a seek_callback is not \c NULL then a
1447 *                            \a tell_callback must also be supplied.
1448 *                            Alternatively, a dummy tell callback that just
1449 *                            returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
1450 *                            may also be supplied, all though this is slightly
1451 *                            less efficient for the encoder.
1452 * \param  metadata_callback  See FLAC__StreamEncoderMetadataCallback.  This
1453 *                            pointer may be \c NULL if the callback is not
1454 *                            desired.  If the client provides a seek callback,
1455 *                            this function is not necessary as the encoder
1456 *                            will automatically seek back and update the
1457 *                            STREAMINFO block.  It may also be \c NULL if the
1458 *                            client does not support seeking, since it will
1459 *                            have no way of going back to update the
1460 *                            STREAMINFO.  However the client can still supply
1461 *                            a callback if it would like to know the details
1462 *                            from the STREAMINFO.
1463 * \param  client_data        This value will be supplied to callbacks in their
1464 *                            \a client_data argument.
1465 * \assert
1466 *    \code encoder != NULL \endcode
1467 * \retval FLAC__StreamEncoderInitStatus
1468 *    \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
1469 *    see FLAC__StreamEncoderInitStatus for the meanings of other return values.
1470 */
1471FLAC_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);
1472
1473/** Initialize the encoder instance to encode Ogg FLAC streams.
1474 *
1475 *  This flavor of initialization sets up the encoder to encode to a FLAC
1476 *  stream in an Ogg container.  I/O is performed via callbacks to the
1477 *  client.  For encoding to a plain file via filename or open \c FILE*,
1478 *  FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
1479 *  provide a simpler interface.
1480 *
1481 *  This function should be called after FLAC__stream_encoder_new() and
1482 *  FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
1483 *  or FLAC__stream_encoder_process_interleaved().
1484 *  initialization succeeded.
1485 *
1486 *  The call to FLAC__stream_encoder_init_ogg_stream() currently will also
1487 *  immediately call the write callback several times to write the metadata
1488 *  packets.
1489 *
1490 * \param  encoder            An uninitialized encoder instance.
1491 * \param  read_callback      See FLAC__StreamEncoderReadCallback.  This
1492 *                            pointer must not be \c NULL if \a seek_callback
1493 *                            is non-NULL since they are both needed to be
1494 *                            able to write data back to the Ogg FLAC stream
1495 *                            in the post-encode phase.
1496 * \param  write_callback     See FLAC__StreamEncoderWriteCallback.  This
1497 *                            pointer must not be \c NULL.
1498 * \param  seek_callback      See FLAC__StreamEncoderSeekCallback.  This
1499 *                            pointer may be \c NULL if seeking is not
1500 *                            supported.  The encoder uses seeking to go back
1501 *                            and write some some stream statistics to the
1502 *                            STREAMINFO block; this is recommended but not
1503 *                            necessary to create a valid FLAC stream.  If
1504 *                            \a seek_callback is not \c NULL then a
1505 *                            \a tell_callback must also be supplied.
1506 *                            Alternatively, a dummy seek callback that just
1507 *                            returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
1508 *                            may also be supplied, all though this is slightly
1509 *                            less efficient for the encoder.
1510 * \param  tell_callback      See FLAC__StreamEncoderTellCallback.  This
1511 *                            pointer may be \c NULL if seeking is not
1512 *                            supported.  If \a seek_callback is \c NULL then
1513 *                            this argument will be ignored.  If
1514 *                            \a seek_callback is not \c NULL then a
1515 *                            \a tell_callback must also be supplied.
1516 *                            Alternatively, a dummy tell callback that just
1517 *                            returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
1518 *                            may also be supplied, all though this is slightly
1519 *                            less efficient for the encoder.
1520 * \param  metadata_callback  See FLAC__StreamEncoderMetadataCallback.  This
1521 *                            pointer may be \c NULL if the callback is not
1522 *                            desired.  If the client provides a seek callback,
1523 *                            this function is not necessary as the encoder
1524 *                            will automatically seek back and update the
1525 *                            STREAMINFO block.  It may also be \c NULL if the
1526 *                            client does not support seeking, since it will
1527 *                            have no way of going back to update the
1528 *                            STREAMINFO.  However the client can still supply
1529 *                            a callback if it would like to know the details
1530 *                            from the STREAMINFO.
1531 * \param  client_data        This value will be supplied to callbacks in their
1532 *                            \a client_data argument.
1533 * \assert
1534 *    \code encoder != NULL \endcode
1535 * \retval FLAC__StreamEncoderInitStatus
1536 *    \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
1537 *    see FLAC__StreamEncoderInitStatus for the meanings of other return values.
1538 */
1539FLAC_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);
1540
1541/** Initialize the encoder instance to encode native FLAC files.
1542 *
1543 *  This flavor of initialization sets up the encoder to encode to a
1544 *  plain native FLAC file.  For non-stdio streams, you must use
1545 *  FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
1546 *
1547 *  This function should be called after FLAC__stream_encoder_new() and
1548 *  FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
1549 *  or FLAC__stream_encoder_process_interleaved().
1550 *  initialization succeeded.
1551 *
1552 * \param  encoder            An uninitialized encoder instance.
1553 * \param  file               An open file.  The file should have been opened
1554 *                            with mode \c "w+b" and rewound.  The file
1555 *                            becomes owned by the encoder and should not be
1556 *                            manipulated by the client while encoding.
1557 *                            Unless \a file is \c stdout, it will be closed
1558 *                            when FLAC__stream_encoder_finish() is called.
1559 *                            Note however that a proper SEEKTABLE cannot be
1560 *                            created when encoding to \c stdout since it is
1561 *                            not seekable.
1562 * \param  progress_callback  See FLAC__StreamEncoderProgressCallback.  This
1563 *                            pointer may be \c NULL if the callback is not
1564 *                            desired.
1565 * \param  client_data        This value will be supplied to callbacks in their
1566 *                            \a client_data argument.
1567 * \assert
1568 *    \code encoder != NULL \endcode
1569 *    \code file != NULL \endcode
1570 * \retval FLAC__StreamEncoderInitStatus
1571 *    \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
1572 *    see FLAC__StreamEncoderInitStatus for the meanings of other return values.
1573 */
1574FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
1575
1576/** Initialize the encoder instance to encode Ogg FLAC files.
1577 *
1578 *  This flavor of initialization sets up the encoder to encode to a
1579 *  plain Ogg FLAC file.  For non-stdio streams, you must use
1580 *  FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
1581 *
1582 *  This function should be called after FLAC__stream_encoder_new() and
1583 *  FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
1584 *  or FLAC__stream_encoder_process_interleaved().
1585 *  initialization succeeded.
1586 *
1587 * \param  encoder            An uninitialized encoder instance.
1588 * \param  file               An open file.  The file should have been opened
1589 *                            with mode \c "w+b" and rewound.  The file
1590 *                            becomes owned by the encoder and should not be
1591 *                            manipulated by the client while encoding.
1592 *                            Unless \a file is \c stdout, it will be closed
1593 *                            when FLAC__stream_encoder_finish() is called.
1594 *                            Note however that a proper SEEKTABLE cannot be
1595 *                            created when encoding to \c stdout since it is
1596 *                            not seekable.
1597 * \param  progress_callback  See FLAC__StreamEncoderProgressCallback.  This
1598 *                            pointer may be \c NULL if the callback is not
1599 *                            desired.
1600 * \param  client_data        This value will be supplied to callbacks in their
1601 *                            \a client_data argument.
1602 * \assert
1603 *    \code encoder != NULL \endcode
1604 *    \code file != NULL \endcode
1605 * \retval FLAC__StreamEncoderInitStatus
1606 *    \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
1607 *    see FLAC__StreamEncoderInitStatus for the meanings of other return values.
1608 */
1609FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
1610
1611/** Initialize the encoder instance to encode native FLAC files.
1612 *
1613 *  This flavor of initialization sets up the encoder to encode to a plain
1614 *  FLAC file.  If POSIX fopen() semantics are not sufficient (for example,
1615 *  with Unicode filenames on Windows), you must use
1616 *  FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
1617 *  and provide callbacks for the I/O.
1618 *
1619 *  This function should be called after FLAC__stream_encoder_new() and
1620 *  FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
1621 *  or FLAC__stream_encoder_process_interleaved().
1622 *  initialization succeeded.
1623 *
1624 * \param  encoder            An uninitialized encoder instance.
1625 * \param  filename           The name of the file to encode to.  The file will
1626 *                            be opened with fopen().  Use \c NULL to encode to
1627 *                            \c stdout.  Note however that a proper SEEKTABLE
1628 *                            cannot be created when encoding to \c stdout since
1629 *                            it is not seekable.
1630 * \param  progress_callback  See FLAC__StreamEncoderProgressCallback.  This
1631 *                            pointer may be \c NULL if the callback is not
1632 *                            desired.
1633 * \param  client_data        This value will be supplied to callbacks in their
1634 *                            \a client_data argument.
1635 * \assert
1636 *    \code encoder != NULL \endcode
1637 * \retval FLAC__StreamEncoderInitStatus
1638 *    \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
1639 *    see FLAC__StreamEncoderInitStatus for the meanings of other return values.
1640 */
1641FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
1642
1643/** Initialize the encoder instance to encode Ogg FLAC files.
1644 *
1645 *  This flavor of initialization sets up the encoder to encode to a plain
1646 *  Ogg FLAC file.  If POSIX fopen() semantics are not sufficient (for example,
1647 *  with Unicode filenames on Windows), you must use
1648 *  FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
1649 *  and provide callbacks for the I/O.
1650 *
1651 *  This function should be called after FLAC__stream_encoder_new() and
1652 *  FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
1653 *  or FLAC__stream_encoder_process_interleaved().
1654 *  initialization succeeded.
1655 *
1656 * \param  encoder            An uninitialized encoder instance.
1657 * \param  filename           The name of the file to encode to.  The file will
1658 *                            be opened with fopen().  Use \c NULL to encode to
1659 *                            \c stdout.  Note however that a proper SEEKTABLE
1660 *                            cannot be created when encoding to \c stdout since
1661 *                            it is not seekable.
1662 * \param  progress_callback  See FLAC__StreamEncoderProgressCallback.  This
1663 *                            pointer may be \c NULL if the callback is not
1664 *                            desired.
1665 * \param  client_data        This value will be supplied to callbacks in their
1666 *                            \a client_data argument.
1667 * \assert
1668 *    \code encoder != NULL \endcode
1669 * \retval FLAC__StreamEncoderInitStatus
1670 *    \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
1671 *    see FLAC__StreamEncoderInitStatus for the meanings of other return values.
1672 */
1673FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
1674
1675/** Finish the encoding process.
1676 *  Flushes the encoding buffer, releases resources, resets the encoder
1677 *  settings to their defaults, and returns the encoder state to
1678 *  FLAC__STREAM_ENCODER_UNINITIALIZED.  Note that this can generate
1679 *  one or more write callbacks before returning, and will generate
1680 *  a metadata callback.
1681 *
1682 *  Note that in the course of processing the last frame, errors can
1683 *  occur, so the caller should be sure to check the return value to
1684 *  ensure the file was encoded properly.
1685 *
1686 *  In the event of a prematurely-terminated encode, it is not strictly
1687 *  necessary to call this immediately before FLAC__stream_encoder_delete()
1688 *  but it is good practice to match every FLAC__stream_encoder_init_*()
1689 *  with a FLAC__stream_encoder_finish().
1690 *
1691 * \param  encoder  An uninitialized encoder instance.
1692 * \assert
1693 *    \code encoder != NULL \endcode
1694 * \retval FLAC__bool
1695 *    \c false if an error occurred processing the last frame; or if verify
1696 *    mode is set (see FLAC__stream_encoder_set_verify()), there was a
1697 *    verify mismatch; else \c true.  If \c false, caller should check the
1698 *    state with FLAC__stream_encoder_get_state() for more information
1699 *    about the error.
1700 */
1701FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
1702
1703/** Submit data for encoding.
1704 *  This version allows you to supply the input data via an array of
1705 *  pointers, each pointer pointing to an array of \a samples samples
1706 *  representing one channel.  The samples need not be block-aligned,
1707 *  but each channel should have the same number of samples.  Each sample
1708 *  should be a signed integer, right-justified to the resolution set by
1709 *  FLAC__stream_encoder_set_bits_per_sample().  For example, if the
1710 *  resolution is 16 bits per sample, the samples should all be in the
1711 *  range [-32768,32767].
1712 *
1713 *  For applications where channel order is important, channels must
1714 *  follow the order as described in the
1715 *  <A HREF="../format.html#frame_header">frame header</A>.
1716 *
1717 * \param  encoder  An initialized encoder instance in the OK state.
1718 * \param  buffer   An array of pointers to each channel's signal.
1719 * \param  samples  The number of samples in one channel.
1720 * \assert
1721 *    \code encoder != NULL \endcode
1722 *    \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
1723 * \retval FLAC__bool
1724 *    \c true if successful, else \c false; in this case, check the
1725 *    encoder state with FLAC__stream_encoder_get_state() to see what
1726 *    went wrong.
1727 */
1728FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
1729
1730/** Submit data for encoding.
1731 *  This version allows you to supply the input data where the channels
1732 *  are interleaved into a single array (i.e. channel0_sample0,
1733 *  channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
1734 *  The samples need not be block-aligned but they must be
1735 *  sample-aligned, i.e. the first value should be channel0_sample0
1736 *  and the last value channelN_sampleM.  Each sample should be a signed
1737 *  integer, right-justified to the resolution set by
1738 *  FLAC__stream_encoder_set_bits_per_sample().  For example, if the
1739 *  resolution is 16 bits per sample, the samples should all be in the
1740 *  range [-32768,32767].
1741 *
1742 *  For applications where channel order is important, channels must
1743 *  follow the order as described in the
1744 *  <A HREF="../format.html#frame_header">frame header</A>.
1745 *
1746 * \param  encoder  An initialized encoder instance in the OK state.
1747 * \param  buffer   An array of channel-interleaved data (see above).
1748 * \param  samples  The number of samples in one channel, the same as for
1749 *                  FLAC__stream_encoder_process().  For example, if
1750 *                  encoding two channels, \c 1000 \a samples corresponds
1751 *                  to a \a buffer of 2000 values.
1752 * \assert
1753 *    \code encoder != NULL \endcode
1754 *    \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
1755 * \retval FLAC__bool
1756 *    \c true if successful, else \c false; in this case, check the
1757 *    encoder state with FLAC__stream_encoder_get_state() to see what
1758 *    went wrong.
1759 */
1760FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
1761
1762/* \} */
1763
1764#ifdef __cplusplus
1765}
1766#endif
1767
1768#endif
src/lib/libflac/include/flac/ordinals.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__ORDINALS_H
33#define FLAC__ORDINALS_H
34
35#if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
36#include <inttypes.h>
37#endif
38
39typedef signed char FLAC__int8;
40typedef unsigned char FLAC__uint8;
41
42#if defined(_MSC_VER) || defined(__BORLANDC__)
43typedef __int16 FLAC__int16;
44typedef __int32 FLAC__int32;
45typedef __int64 FLAC__int64;
46typedef unsigned __int16 FLAC__uint16;
47typedef unsigned __int32 FLAC__uint32;
48typedef unsigned __int64 FLAC__uint64;
49#elif defined(__EMX__)
50typedef short FLAC__int16;
51typedef long FLAC__int32;
52typedef long long FLAC__int64;
53typedef unsigned short FLAC__uint16;
54typedef unsigned long FLAC__uint32;
55typedef unsigned long long FLAC__uint64;
56#else
57typedef int16_t FLAC__int16;
58typedef int32_t FLAC__int32;
59typedef int64_t FLAC__int64;
60typedef uint16_t FLAC__uint16;
61typedef uint32_t FLAC__uint32;
62typedef uint64_t FLAC__uint64;
63#endif
64
65typedef int FLAC__bool;
66
67typedef FLAC__uint8 FLAC__byte;
68
69#ifdef true
70#undef true
71#endif
72#ifdef false
73#undef false
74#endif
75#ifndef __cplusplus
76#define true 1
77#define false 0
78#endif
79
80#endif
src/lib/libflac/include/flac/callback.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__CALLBACK_H
33#define FLAC__CALLBACK_H
34
35#include "ordinals.h"
36#include <stdlib.h> /* for size_t */
37
38/** \file include/FLAC/callback.h
39 *
40 *  \brief
41 *  This module defines the structures for describing I/O callbacks
42 *  to the other FLAC interfaces.
43 *
44 *  See the detailed documentation for callbacks in the
45 *  \link flac_callbacks callbacks \endlink module.
46 */
47
48/** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
49 *  \ingroup flac
50 *
51 *  \brief
52 *  This module defines the structures for describing I/O callbacks
53 *  to the other FLAC interfaces.
54 *
55 *  The purpose of the I/O callback functions is to create a common way
56 *  for the metadata interfaces to handle I/O.
57 *
58 *  Originally the metadata interfaces required filenames as the way of
59 *  specifying FLAC files to operate on.  This is problematic in some
60 *  environments so there is an additional option to specify a set of
61 *  callbacks for doing I/O on the FLAC file, instead of the filename.
62 *
63 *  In addition to the callbacks, a FLAC__IOHandle type is defined as an
64 *  opaque structure for a data source.
65 *
66 *  The callback function prototypes are similar (but not identical) to the
67 *  stdio functions fread, fwrite, fseek, ftell, feof, and fclose.  If you use
68 *  stdio streams to implement the callbacks, you can pass fread, fwrite, and
69 *  fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
70 *  FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
71 *  is required.  \warning You generally CANNOT directly use fseek or ftell
72 *  for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
73 *  these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
74 *  large files.  You will have to find an equivalent function (e.g. ftello),
75 *  or write a wrapper.  The same is true for feof() since this is usually
76 *  implemented as a macro, not as a function whose address can be taken.
77 *
78 * \{
79 */
80
81#ifdef __cplusplus
82extern "C" {
83#endif
84
85/** This is the opaque handle type used by the callbacks.  Typically
86 *  this is a \c FILE* or address of a file descriptor.
87 */
88typedef void* FLAC__IOHandle;
89
90/** Signature for the read callback.
91 *  The signature and semantics match POSIX fread() implementations
92 *  and can generally be used interchangeably.
93 *
94 * \param  ptr      The address of the read buffer.
95 * \param  size     The size of the records to be read.
96 * \param  nmemb    The number of records to be read.
97 * \param  handle   The handle to the data source.
98 * \retval size_t
99 *    The number of records read.
100 */
101typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
102
103/** Signature for the write callback.
104 *  The signature and semantics match POSIX fwrite() implementations
105 *  and can generally be used interchangeably.
106 *
107 * \param  ptr      The address of the write buffer.
108 * \param  size     The size of the records to be written.
109 * \param  nmemb    The number of records to be written.
110 * \param  handle   The handle to the data source.
111 * \retval size_t
112 *    The number of records written.
113 */
114typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
115
116/** Signature for the seek callback.
117 *  The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
118 *  EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
119 *  and 32-bits wide.
120 *
121 * \param  handle   The handle to the data source.
122 * \param  offset   The new position, relative to \a whence
123 * \param  whence   \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
124 * \retval int
125 *    \c 0 on success, \c -1 on error.
126 */
127typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
128
129/** Signature for the tell callback.
130 *  The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
131 *  EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
132 *  and 32-bits wide.
133 *
134 * \param  handle   The handle to the data source.
135 * \retval FLAC__int64
136 *    The current position on success, \c -1 on error.
137 */
138typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
139
140/** Signature for the EOF callback.
141 *  The signature and semantics mostly match POSIX feof() but WATCHOUT:
142 *  on many systems, feof() is a macro, so in this case a wrapper function
143 *  must be provided instead.
144 *
145 * \param  handle   The handle to the data source.
146 * \retval int
147 *    \c 0 if not at end of file, nonzero if at end of file.
148 */
149typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
150
151/** Signature for the close callback.
152 *  The signature and semantics match POSIX fclose() implementations
153 *  and can generally be used interchangeably.
154 *
155 * \param  handle   The handle to the data source.
156 * \retval int
157 *    \c 0 on success, \c EOF on error.
158 */
159typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
160
161/** A structure for holding a set of callbacks.
162 *  Each FLAC interface that requires a FLAC__IOCallbacks structure will
163 *  describe which of the callbacks are required.  The ones that are not
164 *  required may be set to NULL.
165 *
166 *  If the seek requirement for an interface is optional, you can signify that
167 *  a data sorce is not seekable by setting the \a seek field to \c NULL.
168 */
169typedef struct {
170   FLAC__IOCallback_Read read;
171   FLAC__IOCallback_Write write;
172   FLAC__IOCallback_Seek seek;
173   FLAC__IOCallback_Tell tell;
174   FLAC__IOCallback_Eof eof;
175   FLAC__IOCallback_Close close;
176} FLAC__IOCallbacks;
177
178/* \} */
179
180#ifdef __cplusplus
181}
182#endif
183
184#endif
src/lib/libflac/include/flac/metadata.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__METADATA_H
33#define FLAC__METADATA_H
34
35#include <sys/types.h> /* for off_t */
36#include "export.h"
37#include "callback.h"
38#include "format.h"
39
40/* --------------------------------------------------------------------
41   (For an example of how all these routines are used, see the source
42   code for the unit tests in src/test_libFLAC/metadata_*.c, or
43   metaflac in src/metaflac/)
44   ------------------------------------------------------------------*/
45
46/** \file include/FLAC/metadata.h
47 *
48 *  \brief
49 *  This module provides functions for creating and manipulating FLAC
50 *  metadata blocks in memory, and three progressively more powerful
51 *  interfaces for traversing and editing metadata in FLAC files.
52 *
53 *  See the detailed documentation for each interface in the
54 *  \link flac_metadata metadata \endlink module.
55 */
56
57/** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
58 *  \ingroup flac
59 *
60 *  \brief
61 *  This module provides functions for creating and manipulating FLAC
62 *  metadata blocks in memory, and three progressively more powerful
63 *  interfaces for traversing and editing metadata in native FLAC files.
64 *  Note that currently only the Chain interface (level 2) supports Ogg
65 *  FLAC files, and it is read-only i.e. no writing back changed
66 *  metadata to file.
67 *
68 *  There are three metadata interfaces of increasing complexity:
69 *
70 *  Level 0:
71 *  Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
72 *  PICTURE blocks.
73 *
74 *  Level 1:
75 *  Read-write access to all metadata blocks.  This level is write-
76 *  efficient in most cases (more on this below), and uses less memory
77 *  than level 2.
78 *
79 *  Level 2:
80 *  Read-write access to all metadata blocks.  This level is write-
81 *  efficient in all cases, but uses more memory since all metadata for
82 *  the whole file is read into memory and manipulated before writing
83 *  out again.
84 *
85 *  What do we mean by efficient?  Since FLAC metadata appears at the
86 *  beginning of the file, when writing metadata back to a FLAC file
87 *  it is possible to grow or shrink the metadata such that the entire
88 *  file must be rewritten.  However, if the size remains the same during
89 *  changes or PADDING blocks are utilized, only the metadata needs to be
90 *  overwritten, which is much faster.
91 *
92 *  Efficient means the whole file is rewritten at most one time, and only
93 *  when necessary.  Level 1 is not efficient only in the case that you
94 *  cause more than one metadata block to grow or shrink beyond what can
95 *  be accomodated by padding.  In this case you should probably use level
96 *  2, which allows you to edit all the metadata for a file in memory and
97 *  write it out all at once.
98 *
99 *  All levels know how to skip over and not disturb an ID3v2 tag at the
100 *  front of the file.
101 *
102 *  All levels access files via their filenames.  In addition, level 2
103 *  has additional alternative read and write functions that take an I/O
104 *  handle and callbacks, for situations where access by filename is not
105 *  possible.
106 *
107 *  In addition to the three interfaces, this module defines functions for
108 *  creating and manipulating various metadata objects in memory.  As we see
109 *  from the Format module, FLAC metadata blocks in memory are very primitive
110 *  structures for storing information in an efficient way.  Reading
111 *  information from the structures is easy but creating or modifying them
112 *  directly is more complex.  The metadata object routines here facilitate
113 *  this by taking care of the consistency and memory management drudgery.
114 *
115 *  Unless you will be using the level 1 or 2 interfaces to modify existing
116 *  metadata however, you will not probably not need these.
117 *
118 *  From a dependency standpoint, none of the encoders or decoders require
119 *  the metadata module.  This is so that embedded users can strip out the
120 *  metadata module from libFLAC to reduce the size and complexity.
121 */
122
123#ifdef __cplusplus
124extern "C" {
125#endif
126
127
128/** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
129 *  \ingroup flac_metadata
130 *
131 *  \brief
132 *  The level 0 interface consists of individual routines to read the
133 *  STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
134 *  only a filename.
135 *
136 *  They try to skip any ID3v2 tag at the head of the file.
137 *
138 * \{
139 */
140
141/** Read the STREAMINFO metadata block of the given FLAC file.  This function
142 *  will try to skip any ID3v2 tag at the head of the file.
143 *
144 * \param filename    The path to the FLAC file to read.
145 * \param streaminfo  A pointer to space for the STREAMINFO block.  Since
146 *                    FLAC__StreamMetadata is a simple structure with no
147 *                    memory allocation involved, you pass the address of
148 *                    an existing structure.  It need not be initialized.
149 * \assert
150 *    \code filename != NULL \endcode
151 *    \code streaminfo != NULL \endcode
152 * \retval FLAC__bool
153 *    \c true if a valid STREAMINFO block was read from \a filename.  Returns
154 *    \c false if there was a memory allocation error, a file decoder error,
155 *    or the file contained no STREAMINFO block.  (A memory allocation error
156 *    is possible because this function must set up a file decoder.)
157 */
158FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
159
160/** Read the VORBIS_COMMENT metadata block of the given FLAC file.  This
161 *  function will try to skip any ID3v2 tag at the head of the file.
162 *
163 * \param filename    The path to the FLAC file to read.
164 * \param tags        The address where the returned pointer will be
165 *                    stored.  The \a tags object must be deleted by
166 *                    the caller using FLAC__metadata_object_delete().
167 * \assert
168 *    \code filename != NULL \endcode
169 *    \code tags != NULL \endcode
170 * \retval FLAC__bool
171 *    \c true if a valid VORBIS_COMMENT block was read from \a filename,
172 *    and \a *tags will be set to the address of the metadata structure.
173 *    Returns \c false if there was a memory allocation error, a file
174 *    decoder error, or the file contained no VORBIS_COMMENT block, and
175 *    \a *tags will be set to \c NULL.
176 */
177FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
178
179/** Read the CUESHEET metadata block of the given FLAC file.  This
180 *  function will try to skip any ID3v2 tag at the head of the file.
181 *
182 * \param filename    The path to the FLAC file to read.
183 * \param cuesheet    The address where the returned pointer will be
184 *                    stored.  The \a cuesheet object must be deleted by
185 *                    the caller using FLAC__metadata_object_delete().
186 * \assert
187 *    \code filename != NULL \endcode
188 *    \code cuesheet != NULL \endcode
189 * \retval FLAC__bool
190 *    \c true if a valid CUESHEET block was read from \a filename,
191 *    and \a *cuesheet will be set to the address of the metadata
192 *    structure.  Returns \c false if there was a memory allocation
193 *    error, a file decoder error, or the file contained no CUESHEET
194 *    block, and \a *cuesheet will be set to \c NULL.
195 */
196FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
197
198/** Read a PICTURE metadata block of the given FLAC file.  This
199 *  function will try to skip any ID3v2 tag at the head of the file.
200 *  Since there can be more than one PICTURE block in a file, this
201 *  function takes a number of parameters that act as constraints to
202 *  the search.  The PICTURE block with the largest area matching all
203 *  the constraints will be returned, or \a *picture will be set to
204 *  \c NULL if there was no such block.
205 *
206 * \param filename    The path to the FLAC file to read.
207 * \param picture     The address where the returned pointer will be
208 *                    stored.  The \a picture object must be deleted by
209 *                    the caller using FLAC__metadata_object_delete().
210 * \param type        The desired picture type.  Use \c -1 to mean
211 *                    "any type".
212 * \param mime_type   The desired MIME type, e.g. "image/jpeg".  The
213 *                    string will be matched exactly.  Use \c NULL to
214 *                    mean "any MIME type".
215 * \param description The desired description.  The string will be
216 *                    matched exactly.  Use \c NULL to mean "any
217 *                    description".
218 * \param max_width   The maximum width in pixels desired.  Use
219 *                    \c (unsigned)(-1) to mean "any width".
220 * \param max_height  The maximum height in pixels desired.  Use
221 *                    \c (unsigned)(-1) to mean "any height".
222 * \param max_depth   The maximum color depth in bits-per-pixel desired.
223 *                    Use \c (unsigned)(-1) to mean "any depth".
224 * \param max_colors  The maximum number of colors desired.  Use
225 *                    \c (unsigned)(-1) to mean "any number of colors".
226 * \assert
227 *    \code filename != NULL \endcode
228 *    \code picture != NULL \endcode
229 * \retval FLAC__bool
230 *    \c true if a valid PICTURE block was read from \a filename,
231 *    and \a *picture will be set to the address of the metadata
232 *    structure.  Returns \c false if there was a memory allocation
233 *    error, a file decoder error, or the file contained no PICTURE
234 *    block, and \a *picture will be set to \c NULL.
235 */
236FLAC_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);
237
238/* \} */
239
240
241/** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
242 *  \ingroup flac_metadata
243 *
244 * \brief
245 * The level 1 interface provides read-write access to FLAC file metadata and
246 * operates directly on the FLAC file.
247 *
248 * The general usage of this interface is:
249 *
250 * - Create an iterator using FLAC__metadata_simple_iterator_new()
251 * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
252 *   the exit code.  Call FLAC__metadata_simple_iterator_is_writable() to
253 *   see if the file is writable, or only read access is allowed.
254 * - Use FLAC__metadata_simple_iterator_next() and
255 *   FLAC__metadata_simple_iterator_prev() to traverse the blocks.
256 *   This is does not read the actual blocks themselves.
257 *   FLAC__metadata_simple_iterator_next() is relatively fast.
258 *   FLAC__metadata_simple_iterator_prev() is slower since it needs to search
259 *   forward from the front of the file.
260 * - Use FLAC__metadata_simple_iterator_get_block_type() or
261 *   FLAC__metadata_simple_iterator_get_block() to access the actual data at
262 *   the current iterator position.  The returned object is yours to modify
263 *   and free.
264 * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
265 *   back.  You must have write permission to the original file.  Make sure to
266 *   read the whole comment to FLAC__metadata_simple_iterator_set_block()
267 *   below.
268 * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
269 *   Use the object creation functions from
270 *   \link flac_metadata_object here \endlink to generate new objects.
271 * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
272 *   currently referred to by the iterator, or replace it with padding.
273 * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
274 *   finished.
275 *
276 * \note
277 * The FLAC file remains open the whole time between
278 * FLAC__metadata_simple_iterator_init() and
279 * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
280 * the file during this time.
281 *
282 * \note
283 * Do not modify the \a is_last, \a length, or \a type fields of returned
284 * FLAC__StreamMetadata objects.  These are managed automatically.
285 *
286 * \note
287 * If any of the modification functions
288 * (FLAC__metadata_simple_iterator_set_block(),
289 * FLAC__metadata_simple_iterator_delete_block(),
290 * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
291 * you should delete the iterator as it may no longer be valid.
292 *
293 * \{
294 */
295
296struct FLAC__Metadata_SimpleIterator;
297/** The opaque structure definition for the level 1 iterator type.
298 *  See the
299 *  \link flac_metadata_level1 metadata level 1 module \endlink
300 *  for a detailed description.
301 */
302typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
303
304/** Status type for FLAC__Metadata_SimpleIterator.
305 *
306 *  The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
307 */
308typedef enum {
309
310   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
311   /**< The iterator is in the normal OK state */
312
313   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
314   /**< The data passed into a function violated the function's usage criteria */
315
316   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
317   /**< The iterator could not open the target file */
318
319   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
320   /**< The iterator could not find the FLAC signature at the start of the file */
321
322   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
323   /**< The iterator tried to write to a file that was not writable */
324
325   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
326   /**< The iterator encountered input that does not conform to the FLAC metadata specification */
327
328   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
329   /**< The iterator encountered an error while reading the FLAC file */
330
331   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
332   /**< The iterator encountered an error while seeking in the FLAC file */
333
334   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
335   /**< The iterator encountered an error while writing the FLAC file */
336
337   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
338   /**< The iterator encountered an error renaming the FLAC file */
339
340   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
341   /**< The iterator encountered an error removing the temporary file */
342
343   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
344   /**< Memory allocation failed */
345
346   FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
347   /**< The caller violated an assertion or an unexpected error occurred */
348
349} FLAC__Metadata_SimpleIteratorStatus;
350
351/** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
352 *
353 *  Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
354 *  will give the string equivalent.  The contents should not be modified.
355 */
356extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
357
358
359/** Create a new iterator instance.
360 *
361 * \retval FLAC__Metadata_SimpleIterator*
362 *    \c NULL if there was an error allocating memory, else the new instance.
363 */
364FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
365
366/** Free an iterator instance.  Deletes the object pointed to by \a iterator.
367 *
368 * \param iterator  A pointer to an existing iterator.
369 * \assert
370 *    \code iterator != NULL \endcode
371 */
372FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
373
374/** Get the current status of the iterator.  Call this after a function
375 *  returns \c false to get the reason for the error.  Also resets the status
376 *  to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
377 *
378 * \param iterator  A pointer to an existing iterator.
379 * \assert
380 *    \code iterator != NULL \endcode
381 * \retval FLAC__Metadata_SimpleIteratorStatus
382 *    The current status of the iterator.
383 */
384FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
385
386/** Initialize the iterator to point to the first metadata block in the
387 *  given FLAC file.
388 *
389 * \param iterator             A pointer to an existing iterator.
390 * \param filename             The path to the FLAC file.
391 * \param read_only            If \c true, the FLAC file will be opened
392 *                             in read-only mode; if \c false, the FLAC
393 *                             file will be opened for edit even if no
394 *                             edits are performed.
395 * \param preserve_file_stats  If \c true, the owner and modification
396 *                             time will be preserved even if the FLAC
397 *                             file is written to.
398 * \assert
399 *    \code iterator != NULL \endcode
400 *    \code filename != NULL \endcode
401 * \retval FLAC__bool
402 *    \c false if a memory allocation error occurs, the file can't be
403 *    opened, or another error occurs, else \c true.
404 */
405FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats);
406
407/** Returns \c true if the FLAC file is writable.  If \c false, calls to
408 *  FLAC__metadata_simple_iterator_set_block() and
409 *  FLAC__metadata_simple_iterator_insert_block_after() will fail.
410 *
411 * \param iterator             A pointer to an existing iterator.
412 * \assert
413 *    \code iterator != NULL \endcode
414 * \retval FLAC__bool
415 *    See above.
416 */
417FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
418
419/** Moves the iterator forward one metadata block, returning \c false if
420 *  already at the end.
421 *
422 * \param iterator  A pointer to an existing initialized iterator.
423 * \assert
424 *    \code iterator != NULL \endcode
425 *    \a iterator has been successfully initialized with
426 *    FLAC__metadata_simple_iterator_init()
427 * \retval FLAC__bool
428 *    \c false if already at the last metadata block of the chain, else
429 *    \c true.
430 */
431FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
432
433/** Moves the iterator backward one metadata block, returning \c false if
434 *  already at the beginning.
435 *
436 * \param iterator  A pointer to an existing initialized iterator.
437 * \assert
438 *    \code iterator != NULL \endcode
439 *    \a iterator has been successfully initialized with
440 *    FLAC__metadata_simple_iterator_init()
441 * \retval FLAC__bool
442 *    \c false if already at the first metadata block of the chain, else
443 *    \c true.
444 */
445FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
446
447/** Returns a flag telling if the current metadata block is the last.
448 *
449 * \param iterator  A pointer to an existing initialized iterator.
450 * \assert
451 *    \code iterator != NULL \endcode
452 *    \a iterator has been successfully initialized with
453 *    FLAC__metadata_simple_iterator_init()
454 * \retval FLAC__bool
455 *    \c true if the current metadata block is the last in the file,
456 *    else \c false.
457 */
458FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
459
460/** Get the offset of the metadata block at the current position.  This
461 *  avoids reading the actual block data which can save time for large
462 *  blocks.
463 *
464 * \param iterator  A pointer to an existing initialized iterator.
465 * \assert
466 *    \code iterator != NULL \endcode
467 *    \a iterator has been successfully initialized with
468 *    FLAC__metadata_simple_iterator_init()
469 * \retval off_t
470 *    The offset of the metadata block at the current iterator position.
471 *    This is the byte offset relative to the beginning of the file of
472 *    the current metadata block's header.
473 */
474FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
475
476/** Get the type of the metadata block at the current position.  This
477 *  avoids reading the actual block data which can save time for large
478 *  blocks.
479 *
480 * \param iterator  A pointer to an existing initialized iterator.
481 * \assert
482 *    \code iterator != NULL \endcode
483 *    \a iterator has been successfully initialized with
484 *    FLAC__metadata_simple_iterator_init()
485 * \retval FLAC__MetadataType
486 *    The type of the metadata block at the current iterator position.
487 */
488FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
489
490/** Get the length of the metadata block at the current position.  This
491 *  avoids reading the actual block data which can save time for large
492 *  blocks.
493 *
494 * \param iterator  A pointer to an existing initialized iterator.
495 * \assert
496 *    \code iterator != NULL \endcode
497 *    \a iterator has been successfully initialized with
498 *    FLAC__metadata_simple_iterator_init()
499 * \retval unsigned
500 *    The length of the metadata block at the current iterator position.
501 *    The is same length as that in the
502 *    <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
503 *    i.e. the length of the metadata body that follows the header.
504 */
505FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
506
507/** Get the application ID of the \c APPLICATION block at the current
508 *  position.  This avoids reading the actual block data which can save
509 *  time for large blocks.
510 *
511 * \param iterator  A pointer to an existing initialized iterator.
512 * \param id        A pointer to a buffer of at least \c 4 bytes where
513 *                  the ID will be stored.
514 * \assert
515 *    \code iterator != NULL \endcode
516 *    \code id != NULL \endcode
517 *    \a iterator has been successfully initialized with
518 *    FLAC__metadata_simple_iterator_init()
519 * \retval FLAC__bool
520 *    \c true if the ID was successfully read, else \c false, in which
521 *    case you should check FLAC__metadata_simple_iterator_status() to
522 *    find out why.  If the status is
523 *    \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
524 *    current metadata block is not an \c APPLICATION block.  Otherwise
525 *    if the status is
526 *    \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
527 *    \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
528 *    occurred and the iterator can no longer be used.
529 */
530FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
531
532/** Get the metadata block at the current position.  You can modify the
533 *  block but must use FLAC__metadata_simple_iterator_set_block() to
534 *  write it back to the FLAC file.
535 *
536 *  You must call FLAC__metadata_object_delete() on the returned object
537 *  when you are finished with it.
538 *
539 * \param iterator  A pointer to an existing initialized iterator.
540 * \assert
541 *    \code iterator != NULL \endcode
542 *    \a iterator has been successfully initialized with
543 *    FLAC__metadata_simple_iterator_init()
544 * \retval FLAC__StreamMetadata*
545 *    The current metadata block, or \c NULL if there was a memory
546 *    allocation error.
547 */
548FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
549
550/** Write a block back to the FLAC file.  This function tries to be
551 *  as efficient as possible; how the block is actually written is
552 *  shown by the following:
553 *
554 *  Existing block is a STREAMINFO block and the new block is a
555 *  STREAMINFO block: the new block is written in place.  Make sure
556 *  you know what you're doing when changing the values of a
557 *  STREAMINFO block.
558 *
559 *  Existing block is a STREAMINFO block and the new block is a
560 *  not a STREAMINFO block: this is an error since the first block
561 *  must be a STREAMINFO block.  Returns \c false without altering the
562 *  file.
563 *
564 *  Existing block is not a STREAMINFO block and the new block is a
565 *  STREAMINFO block: this is an error since there may be only one
566 *  STREAMINFO block.  Returns \c false without altering the file.
567 *
568 *  Existing block and new block are the same length: the existing
569 *  block will be replaced by the new block, written in place.
570 *
571 *  Existing block is longer than new block: if use_padding is \c true,
572 *  the existing block will be overwritten in place with the new
573 *  block followed by a PADDING block, if possible, to make the total
574 *  size the same as the existing block.  Remember that a padding
575 *  block requires at least four bytes so if the difference in size
576 *  between the new block and existing block is less than that, the
577 *  entire file will have to be rewritten, using the new block's
578 *  exact size.  If use_padding is \c false, the entire file will be
579 *  rewritten, replacing the existing block by the new block.
580 *
581 *  Existing block is shorter than new block: if use_padding is \c true,
582 *  the function will try and expand the new block into the following
583 *  PADDING block, if it exists and doing so won't shrink the PADDING
584 *  block to less than 4 bytes.  If there is no following PADDING
585 *  block, or it will shrink to less than 4 bytes, or use_padding is
586 *  \c false, the entire file is rewritten, replacing the existing block
587 *  with the new block.  Note that in this case any following PADDING
588 *  block is preserved as is.
589 *
590 *  After writing the block, the iterator will remain in the same
591 *  place, i.e. pointing to the new block.
592 *
593 * \param iterator     A pointer to an existing initialized iterator.
594 * \param block        The block to set.
595 * \param use_padding  See above.
596 * \assert
597 *    \code iterator != NULL \endcode
598 *    \a iterator has been successfully initialized with
599 *    FLAC__metadata_simple_iterator_init()
600 *    \code block != NULL \endcode
601 * \retval FLAC__bool
602 *    \c true if successful, else \c false.
603 */
604FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
605
606/** This is similar to FLAC__metadata_simple_iterator_set_block()
607 *  except that instead of writing over an existing block, it appends
608 *  a block after the existing block.  \a use_padding is again used to
609 *  tell the function to try an expand into following padding in an
610 *  attempt to avoid rewriting the entire file.
611 *
612 *  This function will fail and return \c false if given a STREAMINFO
613 *  block.
614 *
615 *  After writing the block, the iterator will be pointing to the
616 *  new block.
617 *
618 * \param iterator     A pointer to an existing initialized iterator.
619 * \param block        The block to set.
620 * \param use_padding  See above.
621 * \assert
622 *    \code iterator != NULL \endcode
623 *    \a iterator has been successfully initialized with
624 *    FLAC__metadata_simple_iterator_init()
625 *    \code block != NULL \endcode
626 * \retval FLAC__bool
627 *    \c true if successful, else \c false.
628 */
629FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
630
631/** Deletes the block at the current position.  This will cause the
632 *  entire FLAC file to be rewritten, unless \a use_padding is \c true,
633 *  in which case the block will be replaced by an equal-sized PADDING
634 *  block.  The iterator will be left pointing to the block before the
635 *  one just deleted.
636 *
637 *  You may not delete the STREAMINFO block.
638 *
639 * \param iterator     A pointer to an existing initialized iterator.
640 * \param use_padding  See above.
641 * \assert
642 *    \code iterator != NULL \endcode
643 *    \a iterator has been successfully initialized with
644 *    FLAC__metadata_simple_iterator_init()
645 * \retval FLAC__bool
646 *    \c true if successful, else \c false.
647 */
648FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
649
650/* \} */
651
652
653/** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
654 *  \ingroup flac_metadata
655 *
656 * \brief
657 * The level 2 interface provides read-write access to FLAC file metadata;
658 * all metadata is read into memory, operated on in memory, and then written
659 * to file, which is more efficient than level 1 when editing multiple blocks.
660 *
661 * Currently Ogg FLAC is supported for read only, via
662 * FLAC__metadata_chain_read_ogg() but a subsequent
663 * FLAC__metadata_chain_write() will fail.
664 *
665 * The general usage of this interface is:
666 *
667 * - Create a new chain using FLAC__metadata_chain_new().  A chain is a
668 *   linked list of FLAC metadata blocks.
669 * - Read all metadata into the the chain from a FLAC file using
670 *   FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
671 *   check the status.
672 * - Optionally, consolidate the padding using
673 *   FLAC__metadata_chain_merge_padding() or
674 *   FLAC__metadata_chain_sort_padding().
675 * - Create a new iterator using FLAC__metadata_iterator_new()
676 * - Initialize the iterator to point to the first element in the chain
677 *   using FLAC__metadata_iterator_init()
678 * - Traverse the chain using FLAC__metadata_iterator_next and
679 *   FLAC__metadata_iterator_prev().
680 * - Get a block for reading or modification using
681 *   FLAC__metadata_iterator_get_block().  The pointer to the object
682 *   inside the chain is returned, so the block is yours to modify.
683 *   Changes will be reflected in the FLAC file when you write the
684 *   chain.  You can also add and delete blocks (see functions below).
685 * - When done, write out the chain using FLAC__metadata_chain_write().
686 *   Make sure to read the whole comment to the function below.
687 * - Delete the chain using FLAC__metadata_chain_delete().
688 *
689 * \note
690 * Even though the FLAC file is not open while the chain is being
691 * manipulated, you must not alter the file externally during
692 * this time.  The chain assumes the FLAC file will not change
693 * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
694 * and FLAC__metadata_chain_write().
695 *
696 * \note
697 * Do not modify the is_last, length, or type fields of returned
698 * FLAC__StreamMetadata objects.  These are managed automatically.
699 *
700 * \note
701 * The metadata objects returned by FLAC__metadata_iterator_get_block()
702 * are owned by the chain; do not FLAC__metadata_object_delete() them.
703 * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
704 * become owned by the chain and they will be deleted when the chain is
705 * deleted.
706 *
707 * \{
708 */
709
710struct FLAC__Metadata_Chain;
711/** The opaque structure definition for the level 2 chain type.
712 */
713typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
714
715struct FLAC__Metadata_Iterator;
716/** The opaque structure definition for the level 2 iterator type.
717 */
718typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
719
720typedef enum {
721   FLAC__METADATA_CHAIN_STATUS_OK = 0,
722   /**< The chain is in the normal OK state */
723
724   FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
725   /**< The data passed into a function violated the function's usage criteria */
726
727   FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
728   /**< The chain could not open the target file */
729
730   FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
731   /**< The chain could not find the FLAC signature at the start of the file */
732
733   FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
734   /**< The chain tried to write to a file that was not writable */
735
736   FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
737   /**< The chain encountered input that does not conform to the FLAC metadata specification */
738
739   FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
740   /**< The chain encountered an error while reading the FLAC file */
741
742   FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
743   /**< The chain encountered an error while seeking in the FLAC file */
744
745   FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
746   /**< The chain encountered an error while writing the FLAC file */
747
748   FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
749   /**< The chain encountered an error renaming the FLAC file */
750
751   FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
752   /**< The chain encountered an error removing the temporary file */
753
754   FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
755   /**< Memory allocation failed */
756
757   FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
758   /**< The caller violated an assertion or an unexpected error occurred */
759
760   FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
761   /**< One or more of the required callbacks was NULL */
762
763   FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
764   /**< FLAC__metadata_chain_write() was called on a chain read by
765    *   FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
766    *   or
767    *   FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
768    *   was called on a chain read by
769    *   FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
770    *   Matching read/write methods must always be used. */
771
772   FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
773   /**< FLAC__metadata_chain_write_with_callbacks() was called when the
774    *   chain write requires a tempfile; use
775    *   FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
776    *   Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
777    *   called when the chain write does not require a tempfile; use
778    *   FLAC__metadata_chain_write_with_callbacks() instead.
779    *   Always check FLAC__metadata_chain_check_if_tempfile_needed()
780    *   before writing via callbacks. */
781
782} FLAC__Metadata_ChainStatus;
783
784/** Maps a FLAC__Metadata_ChainStatus to a C string.
785 *
786 *  Using a FLAC__Metadata_ChainStatus as the index to this array
787 *  will give the string equivalent.  The contents should not be modified.
788 */
789extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
790
791/*********** FLAC__Metadata_Chain ***********/
792
793/** Create a new chain instance.
794 *
795 * \retval FLAC__Metadata_Chain*
796 *    \c NULL if there was an error allocating memory, else the new instance.
797 */
798FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
799
800/** Free a chain instance.  Deletes the object pointed to by \a chain.
801 *
802 * \param chain  A pointer to an existing chain.
803 * \assert
804 *    \code chain != NULL \endcode
805 */
806FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
807
808/** Get the current status of the chain.  Call this after a function
809 *  returns \c false to get the reason for the error.  Also resets the
810 *  status to FLAC__METADATA_CHAIN_STATUS_OK.
811 *
812 * \param chain    A pointer to an existing chain.
813 * \assert
814 *    \code chain != NULL \endcode
815 * \retval FLAC__Metadata_ChainStatus
816 *    The current status of the chain.
817 */
818FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
819
820/** Read all metadata from a FLAC file into the chain.
821 *
822 * \param chain    A pointer to an existing chain.
823 * \param filename The path to the FLAC file to read.
824 * \assert
825 *    \code chain != NULL \endcode
826 *    \code filename != NULL \endcode
827 * \retval FLAC__bool
828 *    \c true if a valid list of metadata blocks was read from
829 *    \a filename, else \c false.  On failure, check the status with
830 *    FLAC__metadata_chain_status().
831 */
832FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
833
834/** Read all metadata from an Ogg FLAC file into the chain.
835 *
836 * \note Ogg FLAC metadata data writing is not supported yet and
837 * FLAC__metadata_chain_write() will fail.
838 *
839 * \param chain    A pointer to an existing chain.
840 * \param filename The path to the Ogg FLAC file to read.
841 * \assert
842 *    \code chain != NULL \endcode
843 *    \code filename != NULL \endcode
844 * \retval FLAC__bool
845 *    \c true if a valid list of metadata blocks was read from
846 *    \a filename, else \c false.  On failure, check the status with
847 *    FLAC__metadata_chain_status().
848 */
849FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
850
851/** Read all metadata from a FLAC stream into the chain via I/O callbacks.
852 *
853 *  The \a handle need only be open for reading, but must be seekable.
854 *  The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
855 *  for Windows).
856 *
857 * \param chain    A pointer to an existing chain.
858 * \param handle   The I/O handle of the FLAC stream to read.  The
859 *                 handle will NOT be closed after the metadata is read;
860 *                 that is the duty of the caller.
861 * \param callbacks
862 *                 A set of callbacks to use for I/O.  The mandatory
863 *                 callbacks are \a read, \a seek, and \a tell.
864 * \assert
865 *    \code chain != NULL \endcode
866 * \retval FLAC__bool
867 *    \c true if a valid list of metadata blocks was read from
868 *    \a handle, else \c false.  On failure, check the status with
869 *    FLAC__metadata_chain_status().
870 */
871FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
872
873/** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
874 *
875 *  The \a handle need only be open for reading, but must be seekable.
876 *  The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
877 *  for Windows).
878 *
879 * \note Ogg FLAC metadata data writing is not supported yet and
880 * FLAC__metadata_chain_write() will fail.
881 *
882 * \param chain    A pointer to an existing chain.
883 * \param handle   The I/O handle of the Ogg FLAC stream to read.  The
884 *                 handle will NOT be closed after the metadata is read;
885 *                 that is the duty of the caller.
886 * \param callbacks
887 *                 A set of callbacks to use for I/O.  The mandatory
888 *                 callbacks are \a read, \a seek, and \a tell.
889 * \assert
890 *    \code chain != NULL \endcode
891 * \retval FLAC__bool
892 *    \c true if a valid list of metadata blocks was read from
893 *    \a handle, else \c false.  On failure, check the status with
894 *    FLAC__metadata_chain_status().
895 */
896FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
897
898/** Checks if writing the given chain would require the use of a
899 *  temporary file, or if it could be written in place.
900 *
901 *  Under certain conditions, padding can be utilized so that writing
902 *  edited metadata back to the FLAC file does not require rewriting the
903 *  entire file.  If rewriting is required, then a temporary workfile is
904 *  required.  When writing metadata using callbacks, you must check
905 *  this function to know whether to call
906 *  FLAC__metadata_chain_write_with_callbacks() or
907 *  FLAC__metadata_chain_write_with_callbacks_and_tempfile().  When
908 *  writing with FLAC__metadata_chain_write(), the temporary file is
909 *  handled internally.
910 *
911 * \param chain    A pointer to an existing chain.
912 * \param use_padding
913 *                 Whether or not padding will be allowed to be used
914 *                 during the write.  The value of \a use_padding given
915 *                 here must match the value later passed to
916 *                 FLAC__metadata_chain_write_with_callbacks() or
917 *                 FLAC__metadata_chain_write_with_callbacks_with_tempfile().
918 * \assert
919 *    \code chain != NULL \endcode
920 * \retval FLAC__bool
921 *    \c true if writing the current chain would require a tempfile, or
922 *    \c false if metadata can be written in place.
923 */
924FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
925
926/** Write all metadata out to the FLAC file.  This function tries to be as
927 *  efficient as possible; how the metadata is actually written is shown by
928 *  the following:
929 *
930 *  If the current chain is the same size as the existing metadata, the new
931 *  data is written in place.
932 *
933 *  If the current chain is longer than the existing metadata, and
934 *  \a use_padding is \c true, and the last block is a PADDING block of
935 *  sufficient length, the function will truncate the final padding block
936 *  so that the overall size of the metadata is the same as the existing
937 *  metadata, and then just rewrite the metadata.  Otherwise, if not all of
938 *  the above conditions are met, the entire FLAC file must be rewritten.
939 *  If you want to use padding this way it is a good idea to call
940 *  FLAC__metadata_chain_sort_padding() first so that you have the maximum
941 *  amount of padding to work with, unless you need to preserve ordering
942 *  of the PADDING blocks for some reason.
943 *
944 *  If the current chain is shorter than the existing metadata, and
945 *  \a use_padding is \c true, and the final block is a PADDING block, the padding
946 *  is extended to make the overall size the same as the existing data.  If
947 *  \a use_padding is \c true and the last block is not a PADDING block, a new
948 *  PADDING block is added to the end of the new data to make it the same
949 *  size as the existing data (if possible, see the note to
950 *  FLAC__metadata_simple_iterator_set_block() about the four byte limit)
951 *  and the new data is written in place.  If none of the above apply or
952 *  \a use_padding is \c false, the entire FLAC file is rewritten.
953 *
954 *  If \a preserve_file_stats is \c true, the owner and modification time will
955 *  be preserved even if the FLAC file is written.
956 *
957 *  For this write function to be used, the chain must have been read with
958 *  FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
959 *  FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
960 *
961 * \param chain               A pointer to an existing chain.
962 * \param use_padding         See above.
963 * \param preserve_file_stats See above.
964 * \assert
965 *    \code chain != NULL \endcode
966 * \retval FLAC__bool
967 *    \c true if the write succeeded, else \c false.  On failure,
968 *    check the status with FLAC__metadata_chain_status().
969 */
970FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
971
972/** Write all metadata out to a FLAC stream via callbacks.
973 *
974 *  (See FLAC__metadata_chain_write() for the details on how padding is
975 *  used to write metadata in place if possible.)
976 *
977 *  The \a handle must be open for updating and be seekable.  The
978 *  equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
979 *  for Windows).
980 *
981 *  For this write function to be used, the chain must have been read with
982 *  FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
983 *  not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
984 *  Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
985 *  \c false.
986 *
987 * \param chain        A pointer to an existing chain.
988 * \param use_padding  See FLAC__metadata_chain_write()
989 * \param handle       The I/O handle of the FLAC stream to write.  The
990 *                     handle will NOT be closed after the metadata is
991 *                     written; that is the duty of the caller.
992 * \param callbacks    A set of callbacks to use for I/O.  The mandatory
993 *                     callbacks are \a write and \a seek.
994 * \assert
995 *    \code chain != NULL \endcode
996 * \retval FLAC__bool
997 *    \c true if the write succeeded, else \c false.  On failure,
998 *    check the status with FLAC__metadata_chain_status().
999 */
1000FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
1001
1002/** Write all metadata out to a FLAC stream via callbacks.
1003 *
1004 *  (See FLAC__metadata_chain_write() for the details on how padding is
1005 *  used to write metadata in place if possible.)
1006 *
1007 *  This version of the write-with-callbacks function must be used when
1008 *  FLAC__metadata_chain_check_if_tempfile_needed() returns true.  In
1009 *  this function, you must supply an I/O handle corresponding to the
1010 *  FLAC file to edit, and a temporary handle to which the new FLAC
1011 *  file will be written.  It is the caller's job to move this temporary
1012 *  FLAC file on top of the original FLAC file to complete the metadata
1013 *  edit.
1014 *
1015 *  The \a handle must be open for reading and be seekable.  The
1016 *  equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
1017 *  for Windows).
1018 *
1019 *  The \a temp_handle must be open for writing.  The
1020 *  equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
1021 *  for Windows).  It should be an empty stream, or at least positioned
1022 *  at the start-of-file (in which case it is the caller's duty to
1023 *  truncate it on return).
1024 *
1025 *  For this write function to be used, the chain must have been read with
1026 *  FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
1027 *  not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
1028 *  Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
1029 *  \c true.
1030 *
1031 * \param chain        A pointer to an existing chain.
1032 * \param use_padding  See FLAC__metadata_chain_write()
1033 * \param handle       The I/O handle of the original FLAC stream to read.
1034 *                     The handle will NOT be closed after the metadata is
1035 *                     written; that is the duty of the caller.
1036 * \param callbacks    A set of callbacks to use for I/O on \a handle.
1037 *                     The mandatory callbacks are \a read, \a seek, and
1038 *                     \a eof.
1039 * \param temp_handle  The I/O handle of the FLAC stream to write.  The
1040 *                     handle will NOT be closed after the metadata is
1041 *                     written; that is the duty of the caller.
1042 * \param temp_callbacks
1043 *                     A set of callbacks to use for I/O on temp_handle.
1044 *                     The only mandatory callback is \a write.
1045 * \assert
1046 *    \code chain != NULL \endcode
1047 * \retval FLAC__bool
1048 *    \c true if the write succeeded, else \c false.  On failure,
1049 *    check the status with FLAC__metadata_chain_status().
1050 */
1051FLAC_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);
1052
1053/** Merge adjacent PADDING blocks into a single block.
1054 *
1055 * \note This function does not write to the FLAC file, it only
1056 * modifies the chain.
1057 *
1058 * \warning Any iterator on the current chain will become invalid after this
1059 * call.  You should delete the iterator and get a new one.
1060 *
1061 * \param chain               A pointer to an existing chain.
1062 * \assert
1063 *    \code chain != NULL \endcode
1064 */
1065FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
1066
1067/** This function will move all PADDING blocks to the end on the metadata,
1068 *  then merge them into a single block.
1069 *
1070 * \note This function does not write to the FLAC file, it only
1071 * modifies the chain.
1072 *
1073 * \warning Any iterator on the current chain will become invalid after this
1074 * call.  You should delete the iterator and get a new one.
1075 *
1076 * \param chain  A pointer to an existing chain.
1077 * \assert
1078 *    \code chain != NULL \endcode
1079 */
1080FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
1081
1082
1083/*********** FLAC__Metadata_Iterator ***********/
1084
1085/** Create a new iterator instance.
1086 *
1087 * \retval FLAC__Metadata_Iterator*
1088 *    \c NULL if there was an error allocating memory, else the new instance.
1089 */
1090FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
1091
1092/** Free an iterator instance.  Deletes the object pointed to by \a iterator.
1093 *
1094 * \param iterator  A pointer to an existing iterator.
1095 * \assert
1096 *    \code iterator != NULL \endcode
1097 */
1098FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
1099
1100/** Initialize the iterator to point to the first metadata block in the
1101 *  given chain.
1102 *
1103 * \param iterator  A pointer to an existing iterator.
1104 * \param chain     A pointer to an existing and initialized (read) chain.
1105 * \assert
1106 *    \code iterator != NULL \endcode
1107 *    \code chain != NULL \endcode
1108 */
1109FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
1110
1111/** Moves the iterator forward one metadata block, returning \c false if
1112 *  already at the end.
1113 *
1114 * \param iterator  A pointer to an existing initialized iterator.
1115 * \assert
1116 *    \code iterator != NULL \endcode
1117 *    \a iterator has been successfully initialized with
1118 *    FLAC__metadata_iterator_init()
1119 * \retval FLAC__bool
1120 *    \c false if already at the last metadata block of the chain, else
1121 *    \c true.
1122 */
1123FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
1124
1125/** Moves the iterator backward one metadata block, returning \c false if
1126 *  already at the beginning.
1127 *
1128 * \param iterator  A pointer to an existing initialized iterator.
1129 * \assert
1130 *    \code iterator != NULL \endcode
1131 *    \a iterator has been successfully initialized with
1132 *    FLAC__metadata_iterator_init()
1133 * \retval FLAC__bool
1134 *    \c false if already at the first metadata block of the chain, else
1135 *    \c true.
1136 */
1137FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
1138
1139/** Get the type of the metadata block at the current position.
1140 *
1141 * \param iterator  A pointer to an existing initialized iterator.
1142 * \assert
1143 *    \code iterator != NULL \endcode
1144 *    \a iterator has been successfully initialized with
1145 *    FLAC__metadata_iterator_init()
1146 * \retval FLAC__MetadataType
1147 *    The type of the metadata block at the current iterator position.
1148 */
1149FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
1150
1151/** Get the metadata block at the current position.  You can modify
1152 *  the block in place but must write the chain before the changes
1153 *  are reflected to the FLAC file.  You do not need to call
1154 *  FLAC__metadata_iterator_set_block() to reflect the changes;
1155 *  the pointer returned by FLAC__metadata_iterator_get_block()
1156 *  points directly into the chain.
1157 *
1158 * \warning
1159 * Do not call FLAC__metadata_object_delete() on the returned object;
1160 * to delete a block use FLAC__metadata_iterator_delete_block().
1161 *
1162 * \param iterator  A pointer to an existing initialized iterator.
1163 * \assert
1164 *    \code iterator != NULL \endcode
1165 *    \a iterator has been successfully initialized with
1166 *    FLAC__metadata_iterator_init()
1167 * \retval FLAC__StreamMetadata*
1168 *    The current metadata block.
1169 */
1170FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
1171
1172/** Set the metadata block at the current position, replacing the existing
1173 *  block.  The new block passed in becomes owned by the chain and it will be
1174 *  deleted when the chain is deleted.
1175 *
1176 * \param iterator  A pointer to an existing initialized iterator.
1177 * \param block     A pointer to a metadata block.
1178 * \assert
1179 *    \code iterator != NULL \endcode
1180 *    \a iterator has been successfully initialized with
1181 *    FLAC__metadata_iterator_init()
1182 *    \code block != NULL \endcode
1183 * \retval FLAC__bool
1184 *    \c false if the conditions in the above description are not met, or
1185 *    a memory allocation error occurs, otherwise \c true.
1186 */
1187FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
1188
1189/** Removes the current block from the chain.  If \a replace_with_padding is
1190 *  \c true, the block will instead be replaced with a padding block of equal
1191 *  size.  You can not delete the STREAMINFO block.  The iterator will be
1192 *  left pointing to the block before the one just "deleted", even if
1193 *  \a replace_with_padding is \c true.
1194 *
1195 * \param iterator              A pointer to an existing initialized iterator.
1196 * \param replace_with_padding  See above.
1197 * \assert
1198 *    \code iterator != NULL \endcode
1199 *    \a iterator has been successfully initialized with
1200 *    FLAC__metadata_iterator_init()
1201 * \retval FLAC__bool
1202 *    \c false if the conditions in the above description are not met,
1203 *    otherwise \c true.
1204 */
1205FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
1206
1207/** Insert a new block before the current block.  You cannot insert a block
1208 *  before the first STREAMINFO block.  You cannot insert a STREAMINFO block
1209 *  as there can be only one, the one that already exists at the head when you
1210 *  read in a chain.  The chain takes ownership of the new block and it will be
1211 *  deleted when the chain is deleted.  The iterator will be left pointing to
1212 *  the new block.
1213 *
1214 * \param iterator  A pointer to an existing initialized iterator.
1215 * \param block     A pointer to a metadata block to insert.
1216 * \assert
1217 *    \code iterator != NULL \endcode
1218 *    \a iterator has been successfully initialized with
1219 *    FLAC__metadata_iterator_init()
1220 * \retval FLAC__bool
1221 *    \c false if the conditions in the above description are not met, or
1222 *    a memory allocation error occurs, otherwise \c true.
1223 */
1224FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
1225
1226/** Insert a new block after the current block.  You cannot insert a STREAMINFO
1227 *  block as there can be only one, the one that already exists at the head when
1228 *  you read in a chain.  The chain takes ownership of the new block and it will
1229 *  be deleted when the chain is deleted.  The iterator will be left pointing to
1230 *  the new block.
1231 *
1232 * \param iterator  A pointer to an existing initialized iterator.
1233 * \param block     A pointer to a metadata block to insert.
1234 * \assert
1235 *    \code iterator != NULL \endcode
1236 *    \a iterator has been successfully initialized with
1237 *    FLAC__metadata_iterator_init()
1238 * \retval FLAC__bool
1239 *    \c false if the conditions in the above description are not met, or
1240 *    a memory allocation error occurs, otherwise \c true.
1241 */
1242FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
1243
1244/* \} */
1245
1246
1247/** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
1248 *  \ingroup flac_metadata
1249 *
1250 * \brief
1251 * This module contains methods for manipulating FLAC metadata objects.
1252 *
1253 * Since many are variable length we have to be careful about the memory
1254 * management.  We decree that all pointers to data in the object are
1255 * owned by the object and memory-managed by the object.
1256 *
1257 * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
1258 * functions to create all instances.  When using the
1259 * FLAC__metadata_object_set_*() functions to set pointers to data, set
1260 * \a copy to \c true to have the function make it's own copy of the data, or
1261 * to \c false to give the object ownership of your data.  In the latter case
1262 * your pointer must be freeable by free() and will be free()d when the object
1263 * is FLAC__metadata_object_delete()d.  It is legal to pass a null pointer as
1264 * the data pointer to a FLAC__metadata_object_set_*() function as long as
1265 * the length argument is 0 and the \a copy argument is \c false.
1266 *
1267 * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
1268 * will return \c NULL in the case of a memory allocation error, otherwise a new
1269 * object.  The FLAC__metadata_object_set_*() functions return \c false in the
1270 * case of a memory allocation error.
1271 *
1272 * We don't have the convenience of C++ here, so note that the library relies
1273 * on you to keep the types straight.  In other words, if you pass, for
1274 * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
1275 * FLAC__metadata_object_application_set_data(), you will get an assertion
1276 * failure.
1277 *
1278 * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
1279 * maintain a trailing NUL on each Vorbis comment entry.  This is not counted
1280 * toward the length or stored in the stream, but it can make working with plain
1281 * comments (those that don't contain embedded-NULs in the value) easier.
1282 * Entries passed into these functions have trailing NULs added if missing, and
1283 * returned entries are guaranteed to have a trailing NUL.
1284 *
1285 * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
1286 * comment entry/name/value will first validate that it complies with the Vorbis
1287 * comment specification and return false if it does not.
1288 *
1289 * There is no need to recalculate the length field on metadata blocks you
1290 * have modified.  They will be calculated automatically before they  are
1291 * written back to a file.
1292 *
1293 * \{
1294 */
1295
1296
1297/** Create a new metadata object instance of the given type.
1298 *
1299 *  The object will be "empty"; i.e. values and data pointers will be \c 0,
1300 *  with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
1301 *  the vendor string set (but zero comments).
1302 *
1303 *  Do not pass in a value greater than or equal to
1304 *  \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
1305 *  doing.
1306 *
1307 * \param type  Type of object to create
1308 * \retval FLAC__StreamMetadata*
1309 *    \c NULL if there was an error allocating memory or the type code is
1310 *    greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
1311 */
1312FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
1313
1314/** Create a copy of an existing metadata object.
1315 *
1316 *  The copy is a "deep" copy, i.e. dynamically allocated data within the
1317 *  object is also copied.  The caller takes ownership of the new block and
1318 *  is responsible for freeing it with FLAC__metadata_object_delete().
1319 *
1320 * \param object  Pointer to object to copy.
1321 * \assert
1322 *    \code object != NULL \endcode
1323 * \retval FLAC__StreamMetadata*
1324 *    \c NULL if there was an error allocating memory, else the new instance.
1325 */
1326FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
1327
1328/** Free a metadata object.  Deletes the object pointed to by \a object.
1329 *
1330 *  The delete is a "deep" delete, i.e. dynamically allocated data within the
1331 *  object is also deleted.
1332 *
1333 * \param object  A pointer to an existing object.
1334 * \assert
1335 *    \code object != NULL \endcode
1336 */
1337FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
1338
1339/** Compares two metadata objects.
1340 *
1341 *  The compare is "deep", i.e. dynamically allocated data within the
1342 *  object is also compared.
1343 *
1344 * \param block1  A pointer to an existing object.
1345 * \param block2  A pointer to an existing object.
1346 * \assert
1347 *    \code block1 != NULL \endcode
1348 *    \code block2 != NULL \endcode
1349 * \retval FLAC__bool
1350 *    \c true if objects are identical, else \c false.
1351 */
1352FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
1353
1354/** Sets the application data of an APPLICATION block.
1355 *
1356 *  If \a copy is \c true, a copy of the data is stored; otherwise, the object
1357 *  takes ownership of the pointer.  The existing data will be freed if this
1358 *  function is successful, otherwise the original data will remain if \a copy
1359 *  is \c true and malloc() fails.
1360 *
1361 * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
1362 *
1363 * \param object  A pointer to an existing APPLICATION object.
1364 * \param data    A pointer to the data to set.
1365 * \param length  The length of \a data in bytes.
1366 * \param copy    See above.
1367 * \assert
1368 *    \code object != NULL \endcode
1369 *    \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
1370 *    \code (data != NULL && length > 0) ||
1371 * (data == NULL && length == 0 && copy == false) \endcode
1372 * \retval FLAC__bool
1373 *    \c false if \a copy is \c true and malloc() fails, else \c true.
1374 */
1375FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
1376
1377/** Resize the seekpoint array.
1378 *
1379 *  If the size shrinks, elements will truncated; if it grows, new placeholder
1380 *  points will be added to the end.
1381 *
1382 * \param object          A pointer to an existing SEEKTABLE object.
1383 * \param new_num_points  The desired length of the array; may be \c 0.
1384 * \assert
1385 *    \code object != NULL \endcode
1386 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1387 *    \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
1388 * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
1389 * \retval FLAC__bool
1390 *    \c false if memory allocation error, else \c true.
1391 */
1392FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
1393
1394/** Set a seekpoint in a seektable.
1395 *
1396 * \param object     A pointer to an existing SEEKTABLE object.
1397 * \param point_num  Index into seekpoint array to set.
1398 * \param point      The point to set.
1399 * \assert
1400 *    \code object != NULL \endcode
1401 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1402 *    \code object->data.seek_table.num_points > point_num \endcode
1403 */
1404FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
1405
1406/** Insert a seekpoint into a seektable.
1407 *
1408 * \param object     A pointer to an existing SEEKTABLE object.
1409 * \param point_num  Index into seekpoint array to set.
1410 * \param point      The point to set.
1411 * \assert
1412 *    \code object != NULL \endcode
1413 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1414 *    \code object->data.seek_table.num_points >= point_num \endcode
1415 * \retval FLAC__bool
1416 *    \c false if memory allocation error, else \c true.
1417 */
1418FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
1419
1420/** Delete a seekpoint from a seektable.
1421 *
1422 * \param object     A pointer to an existing SEEKTABLE object.
1423 * \param point_num  Index into seekpoint array to set.
1424 * \assert
1425 *    \code object != NULL \endcode
1426 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1427 *    \code object->data.seek_table.num_points > point_num \endcode
1428 * \retval FLAC__bool
1429 *    \c false if memory allocation error, else \c true.
1430 */
1431FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
1432
1433/** Check a seektable to see if it conforms to the FLAC specification.
1434 *  See the format specification for limits on the contents of the
1435 *  seektable.
1436 *
1437 * \param object  A pointer to an existing SEEKTABLE object.
1438 * \assert
1439 *    \code object != NULL \endcode
1440 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1441 * \retval FLAC__bool
1442 *    \c false if seek table is illegal, else \c true.
1443 */
1444FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
1445
1446/** Append a number of placeholder points to the end of a seek table.
1447 *
1448 * \note
1449 * As with the other ..._seektable_template_... functions, you should
1450 * call FLAC__metadata_object_seektable_template_sort() when finished
1451 * to make the seek table legal.
1452 *
1453 * \param object  A pointer to an existing SEEKTABLE object.
1454 * \param num     The number of placeholder points to append.
1455 * \assert
1456 *    \code object != NULL \endcode
1457 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1458 * \retval FLAC__bool
1459 *    \c false if memory allocation fails, else \c true.
1460 */
1461FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
1462
1463/** Append a specific seek point template to the end of a seek table.
1464 *
1465 * \note
1466 * As with the other ..._seektable_template_... functions, you should
1467 * call FLAC__metadata_object_seektable_template_sort() when finished
1468 * to make the seek table legal.
1469 *
1470 * \param object  A pointer to an existing SEEKTABLE object.
1471 * \param sample_number  The sample number of the seek point template.
1472 * \assert
1473 *    \code object != NULL \endcode
1474 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1475 * \retval FLAC__bool
1476 *    \c false if memory allocation fails, else \c true.
1477 */
1478FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
1479
1480/** Append specific seek point templates to the end of a seek table.
1481 *
1482 * \note
1483 * As with the other ..._seektable_template_... functions, you should
1484 * call FLAC__metadata_object_seektable_template_sort() when finished
1485 * to make the seek table legal.
1486 *
1487 * \param object  A pointer to an existing SEEKTABLE object.
1488 * \param sample_numbers  An array of sample numbers for the seek points.
1489 * \param num     The number of seek point templates to append.
1490 * \assert
1491 *    \code object != NULL \endcode
1492 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1493 * \retval FLAC__bool
1494 *    \c false if memory allocation fails, else \c true.
1495 */
1496FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
1497
1498/** Append a set of evenly-spaced seek point templates to the end of a
1499 *  seek table.
1500 *
1501 * \note
1502 * As with the other ..._seektable_template_... functions, you should
1503 * call FLAC__metadata_object_seektable_template_sort() when finished
1504 * to make the seek table legal.
1505 *
1506 * \param object  A pointer to an existing SEEKTABLE object.
1507 * \param num     The number of placeholder points to append.
1508 * \param total_samples  The total number of samples to be encoded;
1509 *                       the seekpoints will be spaced approximately
1510 *                       \a total_samples / \a num samples apart.
1511 * \assert
1512 *    \code object != NULL \endcode
1513 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1514 *    \code total_samples > 0 \endcode
1515 * \retval FLAC__bool
1516 *    \c false if memory allocation fails, else \c true.
1517 */
1518FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
1519
1520/** Append a set of evenly-spaced seek point templates to the end of a
1521 *  seek table.
1522 *
1523 * \note
1524 * As with the other ..._seektable_template_... functions, you should
1525 * call FLAC__metadata_object_seektable_template_sort() when finished
1526 * to make the seek table legal.
1527 *
1528 * \param object  A pointer to an existing SEEKTABLE object.
1529 * \param samples The number of samples apart to space the placeholder
1530 *                points.  The first point will be at sample \c 0, the
1531 *                second at sample \a samples, then 2*\a samples, and
1532 *                so on.  As long as \a samples and \a total_samples
1533 *                are greater than \c 0, there will always be at least
1534 *                one seekpoint at sample \c 0.
1535 * \param total_samples  The total number of samples to be encoded;
1536 *                       the seekpoints will be spaced
1537 *                       \a samples samples apart.
1538 * \assert
1539 *    \code object != NULL \endcode
1540 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1541 *    \code samples > 0 \endcode
1542 *    \code total_samples > 0 \endcode
1543 * \retval FLAC__bool
1544 *    \c false if memory allocation fails, else \c true.
1545 */
1546FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
1547
1548/** Sort a seek table's seek points according to the format specification,
1549 *  removing duplicates.
1550 *
1551 * \param object   A pointer to a seek table to be sorted.
1552 * \param compact  If \c false, behaves like FLAC__format_seektable_sort().
1553 *                 If \c true, duplicates are deleted and the seek table is
1554 *                 shrunk appropriately; the number of placeholder points
1555 *                 present in the seek table will be the same after the call
1556 *                 as before.
1557 * \assert
1558 *    \code object != NULL \endcode
1559 *    \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
1560 * \retval FLAC__bool
1561 *    \c false if realloc() fails, else \c true.
1562 */
1563FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
1564
1565/** Sets the vendor string in a VORBIS_COMMENT block.
1566 *
1567 *  For convenience, a trailing NUL is added to the entry if it doesn't have
1568 *  one already.
1569 *
1570 *  If \a copy is \c true, a copy of the entry is stored; otherwise, the object
1571 *  takes ownership of the \c entry.entry pointer.
1572 *
1573 *  \note If this function returns \c false, the caller still owns the
1574 *  pointer.
1575 *
1576 * \param object  A pointer to an existing VORBIS_COMMENT object.
1577 * \param entry   The entry to set the vendor string to.
1578 * \param copy    See above.
1579 * \assert
1580 *    \code object != NULL \endcode
1581 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1582 *    \code (entry.entry != NULL && entry.length > 0) ||
1583 * (entry.entry == NULL && entry.length == 0) \endcode
1584 * \retval FLAC__bool
1585 *    \c false if memory allocation fails or \a entry does not comply with the
1586 *    Vorbis comment specification, else \c true.
1587 */
1588FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
1589
1590/** Resize the comment array.
1591 *
1592 *  If the size shrinks, elements will truncated; if it grows, new empty
1593 *  fields will be added to the end.
1594 *
1595 * \param object            A pointer to an existing VORBIS_COMMENT object.
1596 * \param new_num_comments  The desired length of the array; may be \c 0.
1597 * \assert
1598 *    \code object != NULL \endcode
1599 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1600 *    \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
1601 * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
1602 * \retval FLAC__bool
1603 *    \c false if memory allocation fails, else \c true.
1604 */
1605FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
1606
1607/** Sets a comment in a VORBIS_COMMENT block.
1608 *
1609 *  For convenience, a trailing NUL is added to the entry if it doesn't have
1610 *  one already.
1611 *
1612 *  If \a copy is \c true, a copy of the entry is stored; otherwise, the object
1613 *  takes ownership of the \c entry.entry pointer.
1614 *
1615 *  \note If this function returns \c false, the caller still owns the
1616 *  pointer.
1617 *
1618 * \param object       A pointer to an existing VORBIS_COMMENT object.
1619 * \param comment_num  Index into comment array to set.
1620 * \param entry        The entry to set the comment to.
1621 * \param copy         See above.
1622 * \assert
1623 *    \code object != NULL \endcode
1624 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1625 *    \code comment_num < object->data.vorbis_comment.num_comments \endcode
1626 *    \code (entry.entry != NULL && entry.length > 0) ||
1627 * (entry.entry == NULL && entry.length == 0) \endcode
1628 * \retval FLAC__bool
1629 *    \c false if memory allocation fails or \a entry does not comply with the
1630 *    Vorbis comment specification, else \c true.
1631 */
1632FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
1633
1634/** Insert a comment in a VORBIS_COMMENT block at the given index.
1635 *
1636 *  For convenience, a trailing NUL is added to the entry if it doesn't have
1637 *  one already.
1638 *
1639 *  If \a copy is \c true, a copy of the entry is stored; otherwise, the object
1640 *  takes ownership of the \c entry.entry pointer.
1641 *
1642 *  \note If this function returns \c false, the caller still owns the
1643 *  pointer.
1644 *
1645 * \param object       A pointer to an existing VORBIS_COMMENT object.
1646 * \param comment_num  The index at which to insert the comment.  The comments
1647 *                     at and after \a comment_num move right one position.
1648 *                     To append a comment to the end, set \a comment_num to
1649 *                     \c object->data.vorbis_comment.num_comments .
1650 * \param entry        The comment to insert.
1651 * \param copy         See above.
1652 * \assert
1653 *    \code object != NULL \endcode
1654 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1655 *    \code object->data.vorbis_comment.num_comments >= comment_num \endcode
1656 *    \code (entry.entry != NULL && entry.length > 0) ||
1657 * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
1658 * \retval FLAC__bool
1659 *    \c false if memory allocation fails or \a entry does not comply with the
1660 *    Vorbis comment specification, else \c true.
1661 */
1662FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
1663
1664/** Appends a comment to a VORBIS_COMMENT block.
1665 *
1666 *  For convenience, a trailing NUL is added to the entry if it doesn't have
1667 *  one already.
1668 *
1669 *  If \a copy is \c true, a copy of the entry is stored; otherwise, the object
1670 *  takes ownership of the \c entry.entry pointer.
1671 *
1672 *  \note If this function returns \c false, the caller still owns the
1673 *  pointer.
1674 *
1675 * \param object       A pointer to an existing VORBIS_COMMENT object.
1676 * \param entry        The comment to insert.
1677 * \param copy         See above.
1678 * \assert
1679 *    \code object != NULL \endcode
1680 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1681 *    \code (entry.entry != NULL && entry.length > 0) ||
1682 * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
1683 * \retval FLAC__bool
1684 *    \c false if memory allocation fails or \a entry does not comply with the
1685 *    Vorbis comment specification, else \c true.
1686 */
1687FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
1688
1689/** Replaces comments in a VORBIS_COMMENT block with a new one.
1690 *
1691 *  For convenience, a trailing NUL is added to the entry if it doesn't have
1692 *  one already.
1693 *
1694 *  Depending on the the value of \a all, either all or just the first comment
1695 *  whose field name(s) match the given entry's name will be replaced by the
1696 *  given entry.  If no comments match, \a entry will simply be appended.
1697 *
1698 *  If \a copy is \c true, a copy of the entry is stored; otherwise, the object
1699 *  takes ownership of the \c entry.entry pointer.
1700 *
1701 *  \note If this function returns \c false, the caller still owns the
1702 *  pointer.
1703 *
1704 * \param object       A pointer to an existing VORBIS_COMMENT object.
1705 * \param entry        The comment to insert.
1706 * \param all          If \c true, all comments whose field name matches
1707 *                     \a entry's field name will be removed, and \a entry will
1708 *                     be inserted at the position of the first matching
1709 *                     comment.  If \c false, only the first comment whose
1710 *                     field name matches \a entry's field name will be
1711 *                     replaced with \a entry.
1712 * \param copy         See above.
1713 * \assert
1714 *    \code object != NULL \endcode
1715 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1716 *    \code (entry.entry != NULL && entry.length > 0) ||
1717 * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
1718 * \retval FLAC__bool
1719 *    \c false if memory allocation fails or \a entry does not comply with the
1720 *    Vorbis comment specification, else \c true.
1721 */
1722FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
1723
1724/** Delete a comment in a VORBIS_COMMENT block at the given index.
1725 *
1726 * \param object       A pointer to an existing VORBIS_COMMENT object.
1727 * \param comment_num  The index of the comment to delete.
1728 * \assert
1729 *    \code object != NULL \endcode
1730 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1731 *    \code object->data.vorbis_comment.num_comments > comment_num \endcode
1732 * \retval FLAC__bool
1733 *    \c false if realloc() fails, else \c true.
1734 */
1735FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
1736
1737/** Creates a Vorbis comment entry from NUL-terminated name and value strings.
1738 *
1739 *  On return, the filled-in \a entry->entry pointer will point to malloc()ed
1740 *  memory and shall be owned by the caller.  For convenience the entry will
1741 *  have a terminating NUL.
1742 *
1743 * \param entry              A pointer to a Vorbis comment entry.  The entry's
1744 *                           \c entry pointer should not point to allocated
1745 *                           memory as it will be overwritten.
1746 * \param field_name         The field name in ASCII, \c NUL terminated.
1747 * \param field_value        The field value in UTF-8, \c NUL terminated.
1748 * \assert
1749 *    \code entry != NULL \endcode
1750 *    \code field_name != NULL \endcode
1751 *    \code field_value != NULL \endcode
1752 * \retval FLAC__bool
1753 *    \c false if malloc() fails, or if \a field_name or \a field_value does
1754 *    not comply with the Vorbis comment specification, else \c true.
1755 */
1756FLAC_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);
1757
1758/** Splits a Vorbis comment entry into NUL-terminated name and value strings.
1759 *
1760 *  The returned pointers to name and value will be allocated by malloc()
1761 *  and shall be owned by the caller.
1762 *
1763 * \param entry              An existing Vorbis comment entry.
1764 * \param field_name         The address of where the returned pointer to the
1765 *                           field name will be stored.
1766 * \param field_value        The address of where the returned pointer to the
1767 *                           field value will be stored.
1768 * \assert
1769 *    \code (entry.entry != NULL && entry.length > 0) \endcode
1770 *    \code memchr(entry.entry, '=', entry.length) != NULL \endcode
1771 *    \code field_name != NULL \endcode
1772 *    \code field_value != NULL \endcode
1773 * \retval FLAC__bool
1774 *    \c false if memory allocation fails or \a entry does not comply with the
1775 *    Vorbis comment specification, else \c true.
1776 */
1777FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value);
1778
1779/** Check if the given Vorbis comment entry's field name matches the given
1780 *  field name.
1781 *
1782 * \param entry              An existing Vorbis comment entry.
1783 * \param field_name         The field name to check.
1784 * \param field_name_length  The length of \a field_name, not including the
1785 *                           terminating \c NUL.
1786 * \assert
1787 *    \code (entry.entry != NULL && entry.length > 0) \endcode
1788 * \retval FLAC__bool
1789 *    \c true if the field names match, else \c false
1790 */
1791FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
1792
1793/** Find a Vorbis comment with the given field name.
1794 *
1795 *  The search begins at entry number \a offset; use an offset of 0 to
1796 *  search from the beginning of the comment array.
1797 *
1798 * \param object      A pointer to an existing VORBIS_COMMENT object.
1799 * \param offset      The offset into the comment array from where to start
1800 *                    the search.
1801 * \param field_name  The field name of the comment to find.
1802 * \assert
1803 *    \code object != NULL \endcode
1804 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1805 *    \code field_name != NULL \endcode
1806 * \retval int
1807 *    The offset in the comment array of the first comment whose field
1808 *    name matches \a field_name, or \c -1 if no match was found.
1809 */
1810FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
1811
1812/** Remove first Vorbis comment matching the given field name.
1813 *
1814 * \param object      A pointer to an existing VORBIS_COMMENT object.
1815 * \param field_name  The field name of comment to delete.
1816 * \assert
1817 *    \code object != NULL \endcode
1818 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1819 * \retval int
1820 *    \c -1 for memory allocation error, \c 0 for no matching entries,
1821 *    \c 1 for one matching entry deleted.
1822 */
1823FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
1824
1825/** Remove all Vorbis comments matching the given field name.
1826 *
1827 * \param object      A pointer to an existing VORBIS_COMMENT object.
1828 * \param field_name  The field name of comments to delete.
1829 * \assert
1830 *    \code object != NULL \endcode
1831 *    \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
1832 * \retval int
1833 *    \c -1 for memory allocation error, \c 0 for no matching entries,
1834 *    else the number of matching entries deleted.
1835 */
1836FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
1837
1838/** Create a new CUESHEET track instance.
1839 *
1840 *  The object will be "empty"; i.e. values and data pointers will be \c 0.
1841 *
1842 * \retval FLAC__StreamMetadata_CueSheet_Track*
1843 *    \c NULL if there was an error allocating memory, else the new instance.
1844 */
1845FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
1846
1847/** Create a copy of an existing CUESHEET track object.
1848 *
1849 *  The copy is a "deep" copy, i.e. dynamically allocated data within the
1850 *  object is also copied.  The caller takes ownership of the new object and
1851 *  is responsible for freeing it with
1852 *  FLAC__metadata_object_cuesheet_track_delete().
1853 *
1854 * \param object  Pointer to object to copy.
1855 * \assert
1856 *    \code object != NULL \endcode
1857 * \retval FLAC__StreamMetadata_CueSheet_Track*
1858 *    \c NULL if there was an error allocating memory, else the new instance.
1859 */
1860FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
1861
1862/** Delete a CUESHEET track object
1863 *
1864 * \param object       A pointer to an existing CUESHEET track object.
1865 * \assert
1866 *    \code object != NULL \endcode
1867 */
1868FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
1869
1870/** Resize a track's index point array.
1871 *
1872 *  If the size shrinks, elements will truncated; if it grows, new blank
1873 *  indices will be added to the end.
1874 *
1875 * \param object           A pointer to an existing CUESHEET object.
1876 * \param track_num        The index of the track to modify.  NOTE: this is not
1877 *                         necessarily the same as the track's \a number field.
1878 * \param new_num_indices  The desired length of the array; may be \c 0.
1879 * \assert
1880 *    \code object != NULL \endcode
1881 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
1882 *    \code object->data.cue_sheet.num_tracks > track_num \endcode
1883 *    \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
1884 * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
1885 * \retval FLAC__bool
1886 *    \c false if memory allocation error, else \c true.
1887 */
1888FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
1889
1890/** Insert an index point in a CUESHEET track at the given index.
1891 *
1892 * \param object       A pointer to an existing CUESHEET object.
1893 * \param track_num    The index of the track to modify.  NOTE: this is not
1894 *                     necessarily the same as the track's \a number field.
1895 * \param index_num    The index into the track's index array at which to
1896 *                     insert the index point.  NOTE: this is not necessarily
1897 *                     the same as the index point's \a number field.  The
1898 *                     indices at and after \a index_num move right one
1899 *                     position.  To append an index point to the end, set
1900 *                     \a index_num to
1901 *                     \c object->data.cue_sheet.tracks[track_num].num_indices .
1902 * \param index        The index point to insert.
1903 * \assert
1904 *    \code object != NULL \endcode
1905 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
1906 *    \code object->data.cue_sheet.num_tracks > track_num \endcode
1907 *    \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
1908 * \retval FLAC__bool
1909 *    \c false if realloc() fails, else \c true.
1910 */
1911FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index);
1912
1913/** Insert a blank index point in a CUESHEET track at the given index.
1914 *
1915 *  A blank index point is one in which all field values are zero.
1916 *
1917 * \param object       A pointer to an existing CUESHEET object.
1918 * \param track_num    The index of the track to modify.  NOTE: this is not
1919 *                     necessarily the same as the track's \a number field.
1920 * \param index_num    The index into the track's index array at which to
1921 *                     insert the index point.  NOTE: this is not necessarily
1922 *                     the same as the index point's \a number field.  The
1923 *                     indices at and after \a index_num move right one
1924 *                     position.  To append an index point to the end, set
1925 *                     \a index_num to
1926 *                     \c object->data.cue_sheet.tracks[track_num].num_indices .
1927 * \assert
1928 *    \code object != NULL \endcode
1929 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
1930 *    \code object->data.cue_sheet.num_tracks > track_num \endcode
1931 *    \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
1932 * \retval FLAC__bool
1933 *    \c false if realloc() fails, else \c true.
1934 */
1935FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
1936
1937/** Delete an index point in a CUESHEET track at the given index.
1938 *
1939 * \param object       A pointer to an existing CUESHEET object.
1940 * \param track_num    The index into the track array of the track to
1941 *                     modify.  NOTE: this is not necessarily the same
1942 *                     as the track's \a number field.
1943 * \param index_num    The index into the track's index array of the index
1944 *                     to delete.  NOTE: this is not necessarily the same
1945 *                     as the index's \a number field.
1946 * \assert
1947 *    \code object != NULL \endcode
1948 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
1949 *    \code object->data.cue_sheet.num_tracks > track_num \endcode
1950 *    \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
1951 * \retval FLAC__bool
1952 *    \c false if realloc() fails, else \c true.
1953 */
1954FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
1955
1956/** Resize the track array.
1957 *
1958 *  If the size shrinks, elements will truncated; if it grows, new blank
1959 *  tracks will be added to the end.
1960 *
1961 * \param object            A pointer to an existing CUESHEET object.
1962 * \param new_num_tracks    The desired length of the array; may be \c 0.
1963 * \assert
1964 *    \code object != NULL \endcode
1965 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
1966 *    \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
1967 * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
1968 * \retval FLAC__bool
1969 *    \c false if memory allocation error, else \c true.
1970 */
1971FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
1972
1973/** Sets a track in a CUESHEET block.
1974 *
1975 *  If \a copy is \c true, a copy of the track is stored; otherwise, the object
1976 *  takes ownership of the \a track pointer.
1977 *
1978 * \param object       A pointer to an existing CUESHEET object.
1979 * \param track_num    Index into track array to set.  NOTE: this is not
1980 *                     necessarily the same as the track's \a number field.
1981 * \param track        The track to set the track to.  You may safely pass in
1982 *                     a const pointer if \a copy is \c true.
1983 * \param copy         See above.
1984 * \assert
1985 *    \code object != NULL \endcode
1986 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
1987 *    \code track_num < object->data.cue_sheet.num_tracks \endcode
1988 *    \code (track->indices != NULL && track->num_indices > 0) ||
1989 * (track->indices == NULL && track->num_indices == 0)
1990 * \retval FLAC__bool
1991 *    \c false if \a copy is \c true and malloc() fails, else \c true.
1992 */
1993FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
1994
1995/** Insert a track in a CUESHEET block at the given index.
1996 *
1997 *  If \a copy is \c true, a copy of the track is stored; otherwise, the object
1998 *  takes ownership of the \a track pointer.
1999 *
2000 * \param object       A pointer to an existing CUESHEET object.
2001 * \param track_num    The index at which to insert the track.  NOTE: this
2002 *                     is not necessarily the same as the track's \a number
2003 *                     field.  The tracks at and after \a track_num move right
2004 *                     one position.  To append a track to the end, set
2005 *                     \a track_num to \c object->data.cue_sheet.num_tracks .
2006 * \param track        The track to insert.  You may safely pass in a const
2007 *                     pointer if \a copy is \c true.
2008 * \param copy         See above.
2009 * \assert
2010 *    \code object != NULL \endcode
2011 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
2012 *    \code object->data.cue_sheet.num_tracks >= track_num \endcode
2013 * \retval FLAC__bool
2014 *    \c false if \a copy is \c true and malloc() fails, else \c true.
2015 */
2016FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
2017
2018/** Insert a blank track in a CUESHEET block at the given index.
2019 *
2020 *  A blank track is one in which all field values are zero.
2021 *
2022 * \param object       A pointer to an existing CUESHEET object.
2023 * \param track_num    The index at which to insert the track.  NOTE: this
2024 *                     is not necessarily the same as the track's \a number
2025 *                     field.  The tracks at and after \a track_num move right
2026 *                     one position.  To append a track to the end, set
2027 *                     \a track_num to \c object->data.cue_sheet.num_tracks .
2028 * \assert
2029 *    \code object != NULL \endcode
2030 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
2031 *    \code object->data.cue_sheet.num_tracks >= track_num \endcode
2032 * \retval FLAC__bool
2033 *    \c false if \a copy is \c true and malloc() fails, else \c true.
2034 */
2035FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
2036
2037/** Delete a track in a CUESHEET block at the given index.
2038 *
2039 * \param object       A pointer to an existing CUESHEET object.
2040 * \param track_num    The index into the track array of the track to
2041 *                     delete.  NOTE: this is not necessarily the same
2042 *                     as the track's \a number field.
2043 * \assert
2044 *    \code object != NULL \endcode
2045 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
2046 *    \code object->data.cue_sheet.num_tracks > track_num \endcode
2047 * \retval FLAC__bool
2048 *    \c false if realloc() fails, else \c true.
2049 */
2050FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
2051
2052/** Check a cue sheet to see if it conforms to the FLAC specification.
2053 *  See the format specification for limits on the contents of the
2054 *  cue sheet.
2055 *
2056 * \param object     A pointer to an existing CUESHEET object.
2057 * \param check_cd_da_subset  If \c true, check CUESHEET against more
2058 *                   stringent requirements for a CD-DA (audio) disc.
2059 * \param violation  Address of a pointer to a string.  If there is a
2060 *                   violation, a pointer to a string explanation of the
2061 *                   violation will be returned here. \a violation may be
2062 *                   \c NULL if you don't need the returned string.  Do not
2063 *                   free the returned string; it will always point to static
2064 *                   data.
2065 * \assert
2066 *    \code object != NULL \endcode
2067 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
2068 * \retval FLAC__bool
2069 *    \c false if cue sheet is illegal, else \c true.
2070 */
2071FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
2072
2073/** Calculate and return the CDDB/freedb ID for a cue sheet.  The function
2074 *  assumes the cue sheet corresponds to a CD; the result is undefined
2075 *  if the cuesheet's is_cd bit is not set.
2076 *
2077 * \param object     A pointer to an existing CUESHEET object.
2078 * \assert
2079 *    \code object != NULL \endcode
2080 *    \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
2081 * \retval FLAC__uint32
2082 *    The unsigned integer representation of the CDDB/freedb ID
2083 */
2084FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
2085
2086/** Sets the MIME type of a PICTURE block.
2087 *
2088 *  If \a copy is \c true, a copy of the string is stored; otherwise, the object
2089 *  takes ownership of the pointer.  The existing string will be freed if this
2090 *  function is successful, otherwise the original string will remain if \a copy
2091 *  is \c true and malloc() fails.
2092 *
2093 * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
2094 *
2095 * \param object      A pointer to an existing PICTURE object.
2096 * \param mime_type   A pointer to the MIME type string.  The string must be
2097 *                    ASCII characters 0x20-0x7e, NUL-terminated.  No validation
2098 *                    is done.
2099 * \param copy        See above.
2100 * \assert
2101 *    \code object != NULL \endcode
2102 *    \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
2103 *    \code (mime_type != NULL) \endcode
2104 * \retval FLAC__bool
2105 *    \c false if \a copy is \c true and malloc() fails, else \c true.
2106 */
2107FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
2108
2109/** Sets the description of a PICTURE block.
2110 *
2111 *  If \a copy is \c true, a copy of the string is stored; otherwise, the object
2112 *  takes ownership of the pointer.  The existing string will be freed if this
2113 *  function is successful, otherwise the original string will remain if \a copy
2114 *  is \c true and malloc() fails.
2115 *
2116 * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
2117 *
2118 * \param object      A pointer to an existing PICTURE object.
2119 * \param description A pointer to the description string.  The string must be
2120 *                    valid UTF-8, NUL-terminated.  No validation is done.
2121 * \param copy        See above.
2122 * \assert
2123 *    \code object != NULL \endcode
2124 *    \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
2125 *    \code (description != NULL) \endcode
2126 * \retval FLAC__bool
2127 *    \c false if \a copy is \c true and malloc() fails, else \c true.
2128 */
2129FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
2130
2131/** Sets the picture data of a PICTURE block.
2132 *
2133 *  If \a copy is \c true, a copy of the data is stored; otherwise, the object
2134 *  takes ownership of the pointer.  Also sets the \a data_length field of the
2135 *  metadata object to what is passed in as the \a length parameter.  The
2136 *  existing data will be freed if this function is successful, otherwise the
2137 *  original data and data_length will remain if \a copy is \c true and
2138 *  malloc() fails.
2139 *
2140 * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
2141 *
2142 * \param object  A pointer to an existing PICTURE object.
2143 * \param data    A pointer to the data to set.
2144 * \param length  The length of \a data in bytes.
2145 * \param copy    See above.
2146 * \assert
2147 *    \code object != NULL \endcode
2148 *    \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
2149 *    \code (data != NULL && length > 0) ||
2150 * (data == NULL && length == 0 && copy == false) \endcode
2151 * \retval FLAC__bool
2152 *    \c false if \a copy is \c true and malloc() fails, else \c true.
2153 */
2154FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
2155
2156/** Check a PICTURE block to see if it conforms to the FLAC specification.
2157 *  See the format specification for limits on the contents of the
2158 *  PICTURE block.
2159 *
2160 * \param object     A pointer to existing PICTURE block to be checked.
2161 * \param violation  Address of a pointer to a string.  If there is a
2162 *                   violation, a pointer to a string explanation of the
2163 *                   violation will be returned here. \a violation may be
2164 *                   \c NULL if you don't need the returned string.  Do not
2165 *                   free the returned string; it will always point to static
2166 *                   data.
2167 * \assert
2168 *    \code object != NULL \endcode
2169 *    \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
2170 * \retval FLAC__bool
2171 *    \c false if PICTURE block is illegal, else \c true.
2172 */
2173FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
2174
2175/* \} */
2176
2177#ifdef __cplusplus
2178}
2179#endif
2180
2181#endif
src/lib/libflac/include/flac/stream_decoder.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__STREAM_DECODER_H
33#define FLAC__STREAM_DECODER_H
34
35#include <stdio.h> /* for FILE */
36#include "export.h"
37#include "format.h"
38
39#ifdef __cplusplus
40extern "C" {
41#endif
42
43
44/** \file include/FLAC/stream_decoder.h
45 *
46 *  \brief
47 *  This module contains the functions which implement the stream
48 *  decoder.
49 *
50 *  See the detailed documentation in the
51 *  \link flac_stream_decoder stream decoder \endlink module.
52 */
53
54/** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
55 *  \ingroup flac
56 *
57 *  \brief
58 *  This module describes the decoder layers provided by libFLAC.
59 *
60 * The stream decoder can be used to decode complete streams either from
61 * the client via callbacks, or directly from a file, depending on how
62 * it is initialized.  When decoding via callbacks, the client provides
63 * callbacks for reading FLAC data and writing decoded samples, and
64 * handling metadata and errors.  If the client also supplies seek-related
65 * callback, the decoder function for sample-accurate seeking within the
66 * FLAC input is also available.  When decoding from a file, the client
67 * needs only supply a filename or open \c FILE* and write/metadata/error
68 * callbacks; the rest of the callbacks are supplied internally.  For more
69 * info see the \link flac_stream_decoder stream decoder \endlink module.
70 */
71
72/** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
73 *  \ingroup flac_decoder
74 *
75 *  \brief
76 *  This module contains the functions which implement the stream
77 *  decoder.
78 *
79 * The stream decoder can decode native FLAC, and optionally Ogg FLAC
80 * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
81 *
82 * The basic usage of this decoder is as follows:
83 * - The program creates an instance of a decoder using
84 *   FLAC__stream_decoder_new().
85 * - The program overrides the default settings using
86 *   FLAC__stream_decoder_set_*() functions.
87 * - The program initializes the instance to validate the settings and
88 *   prepare for decoding using
89 *   - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
90 *     or FLAC__stream_decoder_init_file() for native FLAC,
91 *   - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
92 *     or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
93 * - The program calls the FLAC__stream_decoder_process_*() functions
94 *   to decode data, which subsequently calls the callbacks.
95 * - The program finishes the decoding with FLAC__stream_decoder_finish(),
96 *   which flushes the input and output and resets the decoder to the
97 *   uninitialized state.
98 * - The instance may be used again or deleted with
99 *   FLAC__stream_decoder_delete().
100 *
101 * In more detail, the program will create a new instance by calling
102 * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
103 * functions to override the default decoder options, and call
104 * one of the FLAC__stream_decoder_init_*() functions.
105 *
106 * There are three initialization functions for native FLAC, one for
107 * setting up the decoder to decode FLAC data from the client via
108 * callbacks, and two for decoding directly from a FLAC file.
109 *
110 * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
111 * You must also supply several callbacks for handling I/O.  Some (like
112 * seeking) are optional, depending on the capabilities of the input.
113 *
114 * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
115 * or FLAC__stream_decoder_init_file().  Then you must only supply an open
116 * \c FILE* or filename and fewer callbacks; the decoder will handle
117 * the other callbacks internally.
118 *
119 * There are three similarly-named init functions for decoding from Ogg
120 * FLAC streams.  Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
121 * library has been built with Ogg support.
122 *
123 * Once the decoder is initialized, your program will call one of several
124 * functions to start the decoding process:
125 *
126 * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
127 *   most one metadata block or audio frame and return, calling either the
128 *   metadata callback or write callback, respectively, once.  If the decoder
129 *   loses sync it will return with only the error callback being called.
130 * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
131 *   to process the stream from the current location and stop upon reaching
132 *   the first audio frame.  The client will get one metadata, write, or error
133 *   callback per metadata block, audio frame, or sync error, respectively.
134 * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
135 *   to process the stream from the current location until the read callback
136 *   returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
137 *   FLAC__STREAM_DECODER_READ_STATUS_ABORT.  The client will get one metadata,
138 *   write, or error callback per metadata block, audio frame, or sync error,
139 *   respectively.
140 *
141 * When the decoder has finished decoding (normally or through an abort),
142 * the instance is finished by calling FLAC__stream_decoder_finish(), which
143 * ensures the decoder is in the correct state and frees memory.  Then the
144 * instance may be deleted with FLAC__stream_decoder_delete() or initialized
145 * again to decode another stream.
146 *
147 * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
148 * At any point after the stream decoder has been initialized, the client can
149 * call this function to seek to an exact sample within the stream.
150 * Subsequently, the first time the write callback is called it will be
151 * passed a (possibly partial) block starting at that sample.
152 *
153 * If the client cannot seek via the callback interface provided, but still
154 * has another way of seeking, it can flush the decoder using
155 * FLAC__stream_decoder_flush() and start feeding data from the new position
156 * through the read callback.
157 *
158 * The stream decoder also provides MD5 signature checking.  If this is
159 * turned on before initialization, FLAC__stream_decoder_finish() will
160 * report when the decoded MD5 signature does not match the one stored
161 * in the STREAMINFO block.  MD5 checking is automatically turned off
162 * (until the next FLAC__stream_decoder_reset()) if there is no signature
163 * in the STREAMINFO block or when a seek is attempted.
164 *
165 * The FLAC__stream_decoder_set_metadata_*() functions deserve special
166 * attention.  By default, the decoder only calls the metadata_callback for
167 * the STREAMINFO block.  These functions allow you to tell the decoder
168 * explicitly which blocks to parse and return via the metadata_callback
169 * and/or which to skip.  Use a FLAC__stream_decoder_set_metadata_respond_all(),
170 * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
171 * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
172 * which blocks to return.  Remember that metadata blocks can potentially
173 * be big (for example, cover art) so filtering out the ones you don't
174 * use can reduce the memory requirements of the decoder.  Also note the
175 * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
176 * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
177 * filtering APPLICATION blocks based on the application ID.
178 *
179 * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
180 * they still can legally be filtered from the metadata_callback.
181 *
182 * \note
183 * The "set" functions may only be called when the decoder is in the
184 * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
185 * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
186 * before FLAC__stream_decoder_init_*().  If this is the case they will
187 * return \c true, otherwise \c false.
188 *
189 * \note
190 * FLAC__stream_decoder_finish() resets all settings to the constructor
191 * defaults, including the callbacks.
192 *
193 * \{
194 */
195
196
197/** State values for a FLAC__StreamDecoder
198 *
199 * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
200 */
201typedef enum {
202
203   FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
204   /**< The decoder is ready to search for metadata. */
205
206   FLAC__STREAM_DECODER_READ_METADATA,
207   /**< The decoder is ready to or is in the process of reading metadata. */
208
209   FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
210   /**< The decoder is ready to or is in the process of searching for the
211    * frame sync code.
212    */
213
214   FLAC__STREAM_DECODER_READ_FRAME,
215   /**< The decoder is ready to or is in the process of reading a frame. */
216
217   FLAC__STREAM_DECODER_END_OF_STREAM,
218   /**< The decoder has reached the end of the stream. */
219
220   FLAC__STREAM_DECODER_OGG_ERROR,
221   /**< An error occurred in the underlying Ogg layer.  */
222
223   FLAC__STREAM_DECODER_SEEK_ERROR,
224   /**< An error occurred while seeking.  The decoder must be flushed
225    * with FLAC__stream_decoder_flush() or reset with
226    * FLAC__stream_decoder_reset() before decoding can continue.
227    */
228
229   FLAC__STREAM_DECODER_ABORTED,
230   /**< The decoder was aborted by the read callback. */
231
232   FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
233   /**< An error occurred allocating memory.  The decoder is in an invalid
234    * state and can no longer be used.
235    */
236
237   FLAC__STREAM_DECODER_UNINITIALIZED
238   /**< The decoder is in the uninitialized state; one of the
239    * FLAC__stream_decoder_init_*() functions must be called before samples
240    * can be processed.
241    */
242
243} FLAC__StreamDecoderState;
244
245/** Maps a FLAC__StreamDecoderState to a C string.
246 *
247 *  Using a FLAC__StreamDecoderState as the index to this array
248 *  will give the string equivalent.  The contents should not be modified.
249 */
250extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
251
252
253/** Possible return values for the FLAC__stream_decoder_init_*() functions.
254 */
255typedef enum {
256
257   FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
258   /**< Initialization was successful. */
259
260   FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
261   /**< The library was not compiled with support for the given container
262    * format.
263    */
264
265   FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
266   /**< A required callback was not supplied. */
267
268   FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
269   /**< An error occurred allocating memory. */
270
271   FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
272   /**< fopen() failed in FLAC__stream_decoder_init_file() or
273    * FLAC__stream_decoder_init_ogg_file(). */
274
275   FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
276   /**< FLAC__stream_decoder_init_*() was called when the decoder was
277    * already initialized, usually because
278    * FLAC__stream_decoder_finish() was not called.
279    */
280
281} FLAC__StreamDecoderInitStatus;
282
283/** Maps a FLAC__StreamDecoderInitStatus to a C string.
284 *
285 *  Using a FLAC__StreamDecoderInitStatus as the index to this array
286 *  will give the string equivalent.  The contents should not be modified.
287 */
288extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
289
290
291/** Return values for the FLAC__StreamDecoder read callback.
292 */
293typedef enum {
294
295   FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
296   /**< The read was OK and decoding can continue. */
297
298   FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
299   /**< The read was attempted while at the end of the stream.  Note that
300    * the client must only return this value when the read callback was
301    * called when already at the end of the stream.  Otherwise, if the read
302    * itself moves to the end of the stream, the client should still return
303    * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
304    * the next read callback it should return
305    * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
306    * of \c 0.
307    */
308
309   FLAC__STREAM_DECODER_READ_STATUS_ABORT
310   /**< An unrecoverable error occurred.  The decoder will return from the process call. */
311
312} FLAC__StreamDecoderReadStatus;
313
314/** Maps a FLAC__StreamDecoderReadStatus to a C string.
315 *
316 *  Using a FLAC__StreamDecoderReadStatus as the index to this array
317 *  will give the string equivalent.  The contents should not be modified.
318 */
319extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
320
321
322/** Return values for the FLAC__StreamDecoder seek callback.
323 */
324typedef enum {
325
326   FLAC__STREAM_DECODER_SEEK_STATUS_OK,
327   /**< The seek was OK and decoding can continue. */
328
329   FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
330   /**< An unrecoverable error occurred.  The decoder will return from the process call. */
331
332   FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
333   /**< Client does not support seeking. */
334
335} FLAC__StreamDecoderSeekStatus;
336
337/** Maps a FLAC__StreamDecoderSeekStatus to a C string.
338 *
339 *  Using a FLAC__StreamDecoderSeekStatus as the index to this array
340 *  will give the string equivalent.  The contents should not be modified.
341 */
342extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
343
344
345/** Return values for the FLAC__StreamDecoder tell callback.
346 */
347typedef enum {
348
349   FLAC__STREAM_DECODER_TELL_STATUS_OK,
350   /**< The tell was OK and decoding can continue. */
351
352   FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
353   /**< An unrecoverable error occurred.  The decoder will return from the process call. */
354
355   FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
356   /**< Client does not support telling the position. */
357
358} FLAC__StreamDecoderTellStatus;
359
360/** Maps a FLAC__StreamDecoderTellStatus to a C string.
361 *
362 *  Using a FLAC__StreamDecoderTellStatus as the index to this array
363 *  will give the string equivalent.  The contents should not be modified.
364 */
365extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
366
367
368/** Return values for the FLAC__StreamDecoder length callback.
369 */
370typedef enum {
371
372   FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
373   /**< The length call was OK and decoding can continue. */
374
375   FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
376   /**< An unrecoverable error occurred.  The decoder will return from the process call. */
377
378   FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
379   /**< Client does not support reporting the length. */
380
381} FLAC__StreamDecoderLengthStatus;
382
383/** Maps a FLAC__StreamDecoderLengthStatus to a C string.
384 *
385 *  Using a FLAC__StreamDecoderLengthStatus as the index to this array
386 *  will give the string equivalent.  The contents should not be modified.
387 */
388extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
389
390
391/** Return values for the FLAC__StreamDecoder write callback.
392 */
393typedef enum {
394
395   FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
396   /**< The write was OK and decoding can continue. */
397
398   FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
399   /**< An unrecoverable error occurred.  The decoder will return from the process call. */
400
401} FLAC__StreamDecoderWriteStatus;
402
403/** Maps a FLAC__StreamDecoderWriteStatus to a C string.
404 *
405 *  Using a FLAC__StreamDecoderWriteStatus as the index to this array
406 *  will give the string equivalent.  The contents should not be modified.
407 */
408extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
409
410
411/** Possible values passed back to the FLAC__StreamDecoder error callback.
412 *  \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
413 *  all.  The rest could be caused by bad sync (false synchronization on
414 *  data that is not the start of a frame) or corrupted data.  The error
415 *  itself is the decoder's best guess at what happened assuming a correct
416 *  sync.  For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
417 *  could be caused by a correct sync on the start of a frame, but some
418 *  data in the frame header was corrupted.  Or it could be the result of
419 *  syncing on a point the stream that looked like the starting of a frame
420 *  but was not.  \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
421 *  could be because the decoder encountered a valid frame made by a future
422 *  version of the encoder which it cannot parse, or because of a false
423 *  sync making it appear as though an encountered frame was generated by
424 *  a future encoder.
425 */
426typedef enum {
427
428   FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
429   /**< An error in the stream caused the decoder to lose synchronization. */
430
431   FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
432   /**< The decoder encountered a corrupted frame header. */
433
434   FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
435   /**< The frame's data did not match the CRC in the footer. */
436
437   FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
438   /**< The decoder encountered reserved fields in use in the stream. */
439
440} FLAC__StreamDecoderErrorStatus;
441
442/** Maps a FLAC__StreamDecoderErrorStatus to a C string.
443 *
444 *  Using a FLAC__StreamDecoderErrorStatus as the index to this array
445 *  will give the string equivalent.  The contents should not be modified.
446 */
447extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
448
449
450/***********************************************************************
451 *
452 * class FLAC__StreamDecoder
453 *
454 ***********************************************************************/
455
456struct FLAC__StreamDecoderProtected;
457struct FLAC__StreamDecoderPrivate;
458/** The opaque structure definition for the stream decoder type.
459 *  See the \link flac_stream_decoder stream decoder module \endlink
460 *  for a detailed description.
461 */
462typedef struct {
463   struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
464   struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
465} FLAC__StreamDecoder;
466
467/** Signature for the read callback.
468 *
469 *  A function pointer matching this signature must be passed to
470 *  FLAC__stream_decoder_init*_stream(). The supplied function will be
471 *  called when the decoder needs more input data.  The address of the
472 *  buffer to be filled is supplied, along with the number of bytes the
473 *  buffer can hold.  The callback may choose to supply less data and
474 *  modify the byte count but must be careful not to overflow the buffer.
475 *  The callback then returns a status code chosen from
476 *  FLAC__StreamDecoderReadStatus.
477 *
478 * Here is an example of a read callback for stdio streams:
479 * \code
480 * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
481 * {
482 *   FILE *file = ((MyClientData*)client_data)->file;
483 *   if(*bytes > 0) {
484 *     *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
485 *     if(ferror(file))
486 *       return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
487 *     else if(*bytes == 0)
488 *       return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
489 *     else
490 *       return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
491 *   }
492 *   else
493 *     return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
494 * }
495 * \endcode
496 *
497 * \note In general, FLAC__StreamDecoder functions which change the
498 * state should not be called on the \a decoder while in the callback.
499 *
500 * \param  decoder  The decoder instance calling the callback.
501 * \param  buffer   A pointer to a location for the callee to store
502 *                  data to be decoded.
503 * \param  bytes    A pointer to the size of the buffer.  On entry
504 *                  to the callback, it contains the maximum number
505 *                  of bytes that may be stored in \a buffer.  The
506 *                  callee must set it to the actual number of bytes
507 *                  stored (0 in case of error or end-of-stream) before
508 *                  returning.
509 * \param  client_data  The callee's client data set through
510 *                      FLAC__stream_decoder_init_*().
511 * \retval FLAC__StreamDecoderReadStatus
512 *    The callee's return status.  Note that the callback should return
513 *    \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
514 *    zero bytes were read and there is no more data to be read.
515 */
516typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
517
518/** Signature for the seek callback.
519 *
520 *  A function pointer matching this signature may be passed to
521 *  FLAC__stream_decoder_init*_stream().  The supplied function will be
522 *  called when the decoder needs to seek the input stream.  The decoder
523 *  will pass the absolute byte offset to seek to, 0 meaning the
524 *  beginning of the stream.
525 *
526 * Here is an example of a seek callback for stdio streams:
527 * \code
528 * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
529 * {
530 *   FILE *file = ((MyClientData*)client_data)->file;
531 *   if(file == stdin)
532 *     return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
533 *   else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
534 *     return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
535 *   else
536 *     return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
537 * }
538 * \endcode
539 *
540 * \note In general, FLAC__StreamDecoder functions which change the
541 * state should not be called on the \a decoder while in the callback.
542 *
543 * \param  decoder  The decoder instance calling the callback.
544 * \param  absolute_byte_offset  The offset from the beginning of the stream
545 *                               to seek to.
546 * \param  client_data  The callee's client data set through
547 *                      FLAC__stream_decoder_init_*().
548 * \retval FLAC__StreamDecoderSeekStatus
549 *    The callee's return status.
550 */
551typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
552
553/** Signature for the tell callback.
554 *
555 *  A function pointer matching this signature may be passed to
556 *  FLAC__stream_decoder_init*_stream().  The supplied function will be
557 *  called when the decoder wants to know the current position of the
558 *  stream.  The callback should return the byte offset from the
559 *  beginning of the stream.
560 *
561 * Here is an example of a tell callback for stdio streams:
562 * \code
563 * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
564 * {
565 *   FILE *file = ((MyClientData*)client_data)->file;
566 *   off_t pos;
567 *   if(file == stdin)
568 *     return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
569 *   else if((pos = ftello(file)) < 0)
570 *     return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
571 *   else {
572 *     *absolute_byte_offset = (FLAC__uint64)pos;
573 *     return FLAC__STREAM_DECODER_TELL_STATUS_OK;
574 *   }
575 * }
576 * \endcode
577 *
578 * \note In general, FLAC__StreamDecoder functions which change the
579 * state should not be called on the \a decoder while in the callback.
580 *
581 * \param  decoder  The decoder instance calling the callback.
582 * \param  absolute_byte_offset  A pointer to storage for the current offset
583 *                               from the beginning of the stream.
584 * \param  client_data  The callee's client data set through
585 *                      FLAC__stream_decoder_init_*().
586 * \retval FLAC__StreamDecoderTellStatus
587 *    The callee's return status.
588 */
589typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
590
591/** Signature for the length callback.
592 *
593 *  A function pointer matching this signature may be passed to
594 *  FLAC__stream_decoder_init*_stream().  The supplied function will be
595 *  called when the decoder wants to know the total length of the stream
596 *  in bytes.
597 *
598 * Here is an example of a length callback for stdio streams:
599 * \code
600 * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
601 * {
602 *   FILE *file = ((MyClientData*)client_data)->file;
603 *   struct stat filestats;
604 *
605 *   if(file == stdin)
606 *     return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
607 *   else if(fstat(fileno(file), &filestats) != 0)
608 *     return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
609 *   else {
610 *     *stream_length = (FLAC__uint64)filestats.st_size;
611 *     return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
612 *   }
613 * }
614 * \endcode
615 *
616 * \note In general, FLAC__StreamDecoder functions which change the
617 * state should not be called on the \a decoder while in the callback.
618 *
619 * \param  decoder  The decoder instance calling the callback.
620 * \param  stream_length  A pointer to storage for the length of the stream
621 *                        in bytes.
622 * \param  client_data  The callee's client data set through
623 *                      FLAC__stream_decoder_init_*().
624 * \retval FLAC__StreamDecoderLengthStatus
625 *    The callee's return status.
626 */
627typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
628
629/** Signature for the EOF callback.
630 *
631 *  A function pointer matching this signature may be passed to
632 *  FLAC__stream_decoder_init*_stream().  The supplied function will be
633 *  called when the decoder needs to know if the end of the stream has
634 *  been reached.
635 *
636 * Here is an example of a EOF callback for stdio streams:
637 * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
638 * \code
639 * {
640 *   FILE *file = ((MyClientData*)client_data)->file;
641 *   return feof(file)? true : false;
642 * }
643 * \endcode
644 *
645 * \note In general, FLAC__StreamDecoder functions which change the
646 * state should not be called on the \a decoder while in the callback.
647 *
648 * \param  decoder  The decoder instance calling the callback.
649 * \param  client_data  The callee's client data set through
650 *                      FLAC__stream_decoder_init_*().
651 * \retval FLAC__bool
652 *    \c true if the currently at the end of the stream, else \c false.
653 */
654typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
655
656/** Signature for the write callback.
657 *
658 *  A function pointer matching this signature must be passed to one of
659 *  the FLAC__stream_decoder_init_*() functions.
660 *  The supplied function will be called when the decoder has decoded a
661 *  single audio frame.  The decoder will pass the frame metadata as well
662 *  as an array of pointers (one for each channel) pointing to the
663 *  decoded audio.
664 *
665 * \note In general, FLAC__StreamDecoder functions which change the
666 * state should not be called on the \a decoder while in the callback.
667 *
668 * \param  decoder  The decoder instance calling the callback.
669 * \param  frame    The description of the decoded frame.  See
670 *                  FLAC__Frame.
671 * \param  buffer   An array of pointers to decoded channels of data.
672 *                  Each pointer will point to an array of signed
673 *                  samples of length \a frame->header.blocksize.
674 *                  Channels will be ordered according to the FLAC
675 *                  specification; see the documentation for the
676 *                  <A HREF="../format.html#frame_header">frame header</A>.
677 * \param  client_data  The callee's client data set through
678 *                      FLAC__stream_decoder_init_*().
679 * \retval FLAC__StreamDecoderWriteStatus
680 *    The callee's return status.
681 */
682typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
683
684/** Signature for the metadata callback.
685 *
686 *  A function pointer matching this signature must be passed to one of
687 *  the FLAC__stream_decoder_init_*() functions.
688 *  The supplied function will be called when the decoder has decoded a
689 *  metadata block.  In a valid FLAC file there will always be one
690 *  \c STREAMINFO block, followed by zero or more other metadata blocks.
691 *  These will be supplied by the decoder in the same order as they
692 *  appear in the stream and always before the first audio frame (i.e.
693 *  write callback).  The metadata block that is passed in must not be
694 *  modified, and it doesn't live beyond the callback, so you should make
695 *  a copy of it with FLAC__metadata_object_clone() if you will need it
696 *  elsewhere.  Since metadata blocks can potentially be large, by
697 *  default the decoder only calls the metadata callback for the
698 *  \c STREAMINFO block; you can instruct the decoder to pass or filter
699 *  other blocks with FLAC__stream_decoder_set_metadata_*() calls.
700 *
701 * \note In general, FLAC__StreamDecoder functions which change the
702 * state should not be called on the \a decoder while in the callback.
703 *
704 * \param  decoder  The decoder instance calling the callback.
705 * \param  metadata The decoded metadata block.
706 * \param  client_data  The callee's client data set through
707 *                      FLAC__stream_decoder_init_*().
708 */
709typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
710
711/** Signature for the error callback.
712 *
713 *  A function pointer matching this signature must be passed to one of
714 *  the FLAC__stream_decoder_init_*() functions.
715 *  The supplied function will be called whenever an error occurs during
716 *  decoding.
717 *
718 * \note In general, FLAC__StreamDecoder functions which change the
719 * state should not be called on the \a decoder while in the callback.
720 *
721 * \param  decoder  The decoder instance calling the callback.
722 * \param  status   The error encountered by the decoder.
723 * \param  client_data  The callee's client data set through
724 *                      FLAC__stream_decoder_init_*().
725 */
726typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
727
728
729/***********************************************************************
730 *
731 * Class constructor/destructor
732 *
733 ***********************************************************************/
734
735/** Create a new stream decoder instance.  The instance is created with
736 *  default settings; see the individual FLAC__stream_decoder_set_*()
737 *  functions for each setting's default.
738 *
739 * \retval FLAC__StreamDecoder*
740 *    \c NULL if there was an error allocating memory, else the new instance.
741 */
742FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
743
744/** Free a decoder instance.  Deletes the object pointed to by \a decoder.
745 *
746 * \param decoder  A pointer to an existing decoder.
747 * \assert
748 *    \code decoder != NULL \endcode
749 */
750FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
751
752
753/***********************************************************************
754 *
755 * Public class method prototypes
756 *
757 ***********************************************************************/
758
759/** Set the serial number for the FLAC stream within the Ogg container.
760 *  The default behavior is to use the serial number of the first Ogg
761 *  page.  Setting a serial number here will explicitly specify which
762 *  stream is to be decoded.
763 *
764 * \note
765 * This does not need to be set for native FLAC decoding.
766 *
767 * \default \c use serial number of first page
768 * \param  decoder        A decoder instance to set.
769 * \param  serial_number  See above.
770 * \assert
771 *    \code decoder != NULL \endcode
772 * \retval FLAC__bool
773 *    \c false if the decoder is already initialized, else \c true.
774 */
775FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
776
777/** Set the "MD5 signature checking" flag.  If \c true, the decoder will
778 *  compute the MD5 signature of the unencoded audio data while decoding
779 *  and compare it to the signature from the STREAMINFO block, if it
780 *  exists, during FLAC__stream_decoder_finish().
781 *
782 *  MD5 signature checking will be turned off (until the next
783 *  FLAC__stream_decoder_reset()) if there is no signature in the
784 *  STREAMINFO block or when a seek is attempted.
785 *
786 *  Clients that do not use the MD5 check should leave this off to speed
787 *  up decoding.
788 *
789 * \default \c false
790 * \param  decoder  A decoder instance to set.
791 * \param  value    Flag value (see above).
792 * \assert
793 *    \code decoder != NULL \endcode
794 * \retval FLAC__bool
795 *    \c false if the decoder is already initialized, else \c true.
796 */
797FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
798
799/** Direct the decoder to pass on all metadata blocks of type \a type.
800 *
801 * \default By default, only the \c STREAMINFO block is returned via the
802 *          metadata callback.
803 * \param  decoder  A decoder instance to set.
804 * \param  type     See above.
805 * \assert
806 *    \code decoder != NULL \endcode
807 *    \a type is valid
808 * \retval FLAC__bool
809 *    \c false if the decoder is already initialized, else \c true.
810 */
811FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
812
813/** Direct the decoder to pass on all APPLICATION metadata blocks of the
814 *  given \a id.
815 *
816 * \default By default, only the \c STREAMINFO block is returned via the
817 *          metadata callback.
818 * \param  decoder  A decoder instance to set.
819 * \param  id       See above.
820 * \assert
821 *    \code decoder != NULL \endcode
822 *    \code id != NULL \endcode
823 * \retval FLAC__bool
824 *    \c false if the decoder is already initialized, else \c true.
825 */
826FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
827
828/** Direct the decoder to pass on all metadata blocks of any type.
829 *
830 * \default By default, only the \c STREAMINFO block is returned via the
831 *          metadata callback.
832 * \param  decoder  A decoder instance to set.
833 * \assert
834 *    \code decoder != NULL \endcode
835 * \retval FLAC__bool
836 *    \c false if the decoder is already initialized, else \c true.
837 */
838FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
839
840/** Direct the decoder to filter out all metadata blocks of type \a type.
841 *
842 * \default By default, only the \c STREAMINFO block is returned via the
843 *          metadata callback.
844 * \param  decoder  A decoder instance to set.
845 * \param  type     See above.
846 * \assert
847 *    \code decoder != NULL \endcode
848 *    \a type is valid
849 * \retval FLAC__bool
850 *    \c false if the decoder is already initialized, else \c true.
851 */
852FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
853
854/** Direct the decoder to filter out all APPLICATION metadata blocks of
855 *  the given \a id.
856 *
857 * \default By default, only the \c STREAMINFO block is returned via the
858 *          metadata callback.
859 * \param  decoder  A decoder instance to set.
860 * \param  id       See above.
861 * \assert
862 *    \code decoder != NULL \endcode
863 *    \code id != NULL \endcode
864 * \retval FLAC__bool
865 *    \c false if the decoder is already initialized, else \c true.
866 */
867FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
868
869/** Direct the decoder to filter out all metadata blocks of any type.
870 *
871 * \default By default, only the \c STREAMINFO block is returned via the
872 *          metadata callback.
873 * \param  decoder  A decoder instance to set.
874 * \assert
875 *    \code decoder != NULL \endcode
876 * \retval FLAC__bool
877 *    \c false if the decoder is already initialized, else \c true.
878 */
879FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
880
881/** Get the current decoder state.
882 *
883 * \param  decoder  A decoder instance to query.
884 * \assert
885 *    \code decoder != NULL \endcode
886 * \retval FLAC__StreamDecoderState
887 *    The current decoder state.
888 */
889FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
890
891/** Get the current decoder state as a C string.
892 *
893 * \param  decoder  A decoder instance to query.
894 * \assert
895 *    \code decoder != NULL \endcode
896 * \retval const char *
897 *    The decoder state as a C string.  Do not modify the contents.
898 */
899FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
900
901/** Get the "MD5 signature checking" flag.
902 *  This is the value of the setting, not whether or not the decoder is
903 *  currently checking the MD5 (remember, it can be turned off automatically
904 *  by a seek).  When the decoder is reset the flag will be restored to the
905 *  value returned by this function.
906 *
907 * \param  decoder  A decoder instance to query.
908 * \assert
909 *    \code decoder != NULL \endcode
910 * \retval FLAC__bool
911 *    See above.
912 */
913FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
914
915/** Get the total number of samples in the stream being decoded.
916 *  Will only be valid after decoding has started and will contain the
917 *  value from the \c STREAMINFO block.  A value of \c 0 means "unknown".
918 *
919 * \param  decoder  A decoder instance to query.
920 * \assert
921 *    \code decoder != NULL \endcode
922 * \retval unsigned
923 *    See above.
924 */
925FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
926
927/** Get the current number of channels in the stream being decoded.
928 *  Will only be valid after decoding has started and will contain the
929 *  value from the most recently decoded frame header.
930 *
931 * \param  decoder  A decoder instance to query.
932 * \assert
933 *    \code decoder != NULL \endcode
934 * \retval unsigned
935 *    See above.
936 */
937FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
938
939/** Get the current channel assignment in the stream being decoded.
940 *  Will only be valid after decoding has started and will contain the
941 *  value from the most recently decoded frame header.
942 *
943 * \param  decoder  A decoder instance to query.
944 * \assert
945 *    \code decoder != NULL \endcode
946 * \retval FLAC__ChannelAssignment
947 *    See above.
948 */
949FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
950
951/** Get the current sample resolution in the stream being decoded.
952 *  Will only be valid after decoding has started and will contain the
953 *  value from the most recently decoded frame header.
954 *
955 * \param  decoder  A decoder instance to query.
956 * \assert
957 *    \code decoder != NULL \endcode
958 * \retval unsigned
959 *    See above.
960 */
961FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
962
963/** Get the current sample rate in Hz of the stream being decoded.
964 *  Will only be valid after decoding has started and will contain the
965 *  value from the most recently decoded frame header.
966 *
967 * \param  decoder  A decoder instance to query.
968 * \assert
969 *    \code decoder != NULL \endcode
970 * \retval unsigned
971 *    See above.
972 */
973FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
974
975/** Get the current blocksize of the stream being decoded.
976 *  Will only be valid after decoding has started and will contain the
977 *  value from the most recently decoded frame header.
978 *
979 * \param  decoder  A decoder instance to query.
980 * \assert
981 *    \code decoder != NULL \endcode
982 * \retval unsigned
983 *    See above.
984 */
985FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
986
987/** Returns the decoder's current read position within the stream.
988 *  The position is the byte offset from the start of the stream.
989 *  Bytes before this position have been fully decoded.  Note that
990 *  there may still be undecoded bytes in the decoder's read FIFO.
991 *  The returned position is correct even after a seek.
992 *
993 *  \warning This function currently only works for native FLAC,
994 *           not Ogg FLAC streams.
995 *
996 * \param  decoder   A decoder instance to query.
997 * \param  position  Address at which to return the desired position.
998 * \assert
999 *    \code decoder != NULL \endcode
1000 *    \code position != NULL \endcode
1001 * \retval FLAC__bool
1002 *    \c true if successful, \c false if the stream is not native FLAC,
1003 *    or there was an error from the 'tell' callback or it returned
1004 *    \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
1005 */
1006FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
1007
1008/** Initialize the decoder instance to decode native FLAC streams.
1009 *
1010 *  This flavor of initialization sets up the decoder to decode from a
1011 *  native FLAC stream. I/O is performed via callbacks to the client.
1012 *  For decoding from a plain file via filename or open FILE*,
1013 *  FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
1014 *  provide a simpler interface.
1015 *
1016 *  This function should be called after FLAC__stream_decoder_new() and
1017 *  FLAC__stream_decoder_set_*() but before any of the
1018 *  FLAC__stream_decoder_process_*() functions.  Will set and return the
1019 *  decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
1020 *  if initialization succeeded.
1021 *
1022 * \param  decoder            An uninitialized decoder instance.
1023 * \param  read_callback      See FLAC__StreamDecoderReadCallback.  This
1024 *                            pointer must not be \c NULL.
1025 * \param  seek_callback      See FLAC__StreamDecoderSeekCallback.  This
1026 *                            pointer may be \c NULL if seeking is not
1027 *                            supported.  If \a seek_callback is not \c NULL then a
1028 *                            \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
1029 *                            Alternatively, a dummy seek callback that just
1030 *                            returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
1031 *                            may also be supplied, all though this is slightly
1032 *                            less efficient for the decoder.
1033 * \param  tell_callback      See FLAC__StreamDecoderTellCallback.  This
1034 *                            pointer may be \c NULL if not supported by the client.  If
1035 *                            \a seek_callback is not \c NULL then a
1036 *                            \a tell_callback must also be supplied.
1037 *                            Alternatively, a dummy tell callback that just
1038 *                            returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
1039 *                            may also be supplied, all though this is slightly
1040 *                            less efficient for the decoder.
1041 * \param  length_callback    See FLAC__StreamDecoderLengthCallback.  This
1042 *                            pointer may be \c NULL if not supported by the client.  If
1043 *                            \a seek_callback is not \c NULL then a
1044 *                            \a length_callback must also be supplied.
1045 *                            Alternatively, a dummy length callback that just
1046 *                            returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
1047 *                            may also be supplied, all though this is slightly
1048 *                            less efficient for the decoder.
1049 * \param  eof_callback       See FLAC__StreamDecoderEofCallback.  This
1050 *                            pointer may be \c NULL if not supported by the client.  If
1051 *                            \a seek_callback is not \c NULL then a
1052 *                            \a eof_callback must also be supplied.
1053 *                            Alternatively, a dummy length callback that just
1054 *                            returns \c false
1055 *                            may also be supplied, all though this is slightly
1056 *                            less efficient for the decoder.
1057 * \param  write_callback     See FLAC__StreamDecoderWriteCallback.  This
1058 *                            pointer must not be \c NULL.
1059 * \param  metadata_callback  See FLAC__StreamDecoderMetadataCallback.  This
1060 *                            pointer may be \c NULL if the callback is not
1061 *                            desired.
1062 * \param  error_callback     See FLAC__StreamDecoderErrorCallback.  This
1063 *                            pointer must not be \c NULL.
1064 * \param  client_data        This value will be supplied to callbacks in their
1065 *                            \a client_data argument.
1066 * \assert
1067 *    \code decoder != NULL \endcode
1068 * \retval FLAC__StreamDecoderInitStatus
1069 *    \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
1070 *    see FLAC__StreamDecoderInitStatus for the meanings of other return values.
1071 */
1072FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
1073   FLAC__StreamDecoder *decoder,
1074   FLAC__StreamDecoderReadCallback read_callback,
1075   FLAC__StreamDecoderSeekCallback seek_callback,
1076   FLAC__StreamDecoderTellCallback tell_callback,
1077   FLAC__StreamDecoderLengthCallback length_callback,
1078   FLAC__StreamDecoderEofCallback eof_callback,
1079   FLAC__StreamDecoderWriteCallback write_callback,
1080   FLAC__StreamDecoderMetadataCallback metadata_callback,
1081   FLAC__StreamDecoderErrorCallback error_callback,
1082   void *client_data
1083);
1084
1085/** Initialize the decoder instance to decode Ogg FLAC streams.
1086 *
1087 *  This flavor of initialization sets up the decoder to decode from a
1088 *  FLAC stream in an Ogg container. I/O is performed via callbacks to the
1089 *  client.  For decoding from a plain file via filename or open FILE*,
1090 *  FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
1091 *  provide a simpler interface.
1092 *
1093 *  This function should be called after FLAC__stream_decoder_new() and
1094 *  FLAC__stream_decoder_set_*() but before any of the
1095 *  FLAC__stream_decoder_process_*() functions.  Will set and return the
1096 *  decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
1097 *  if initialization succeeded.
1098 *
1099 *  \note Support for Ogg FLAC in the library is optional.  If this
1100 *  library has been built without support for Ogg FLAC, this function
1101 *  will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
1102 *
1103 * \param  decoder            An uninitialized decoder instance.
1104 * \param  read_callback      See FLAC__StreamDecoderReadCallback.  This
1105 *                            pointer must not be \c NULL.
1106 * \param  seek_callback      See FLAC__StreamDecoderSeekCallback.  This
1107 *                            pointer may be \c NULL if seeking is not
1108 *                            supported.  If \a seek_callback is not \c NULL then a
1109 *                            \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
1110 *                            Alternatively, a dummy seek callback that just
1111 *                            returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
1112 *                            may also be supplied, all though this is slightly
1113 *                            less efficient for the decoder.
1114 * \param  tell_callback      See FLAC__StreamDecoderTellCallback.  This
1115 *                            pointer may be \c NULL if not supported by the client.  If
1116 *                            \a seek_callback is not \c NULL then a
1117 *                            \a tell_callback must also be supplied.
1118 *                            Alternatively, a dummy tell callback that just
1119 *                            returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
1120 *                            may also be supplied, all though this is slightly
1121 *                            less efficient for the decoder.
1122 * \param  length_callback    See FLAC__StreamDecoderLengthCallback.  This
1123 *                            pointer may be \c NULL if not supported by the client.  If
1124 *                            \a seek_callback is not \c NULL then a
1125 *                            \a length_callback must also be supplied.
1126 *                            Alternatively, a dummy length callback that just
1127 *                            returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
1128 *                            may also be supplied, all though this is slightly
1129 *                            less efficient for the decoder.
1130 * \param  eof_callback       See FLAC__StreamDecoderEofCallback.  This
1131 *                            pointer may be \c NULL if not supported by the client.  If
1132 *                            \a seek_callback is not \c NULL then a
1133 *                            \a eof_callback must also be supplied.
1134 *                            Alternatively, a dummy length callback that just
1135 *                            returns \c false
1136 *                            may also be supplied, all though this is slightly
1137 *                            less efficient for the decoder.
1138 * \param  write_callback     See FLAC__StreamDecoderWriteCallback.  This
1139 *                            pointer must not be \c NULL.
1140 * \param  metadata_callback  See FLAC__StreamDecoderMetadataCallback.  This
1141 *                            pointer may be \c NULL if the callback is not
1142 *                            desired.
1143 * \param  error_callback     See FLAC__StreamDecoderErrorCallback.  This
1144 *                            pointer must not be \c NULL.
1145 * \param  client_data        This value will be supplied to callbacks in their
1146 *                            \a client_data argument.
1147 * \assert
1148 *    \code decoder != NULL \endcode
1149 * \retval FLAC__StreamDecoderInitStatus
1150 *    \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
1151 *    see FLAC__StreamDecoderInitStatus for the meanings of other return values.
1152 */
1153FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
1154   FLAC__StreamDecoder *decoder,
1155   FLAC__StreamDecoderReadCallback read_callback,
1156   FLAC__StreamDecoderSeekCallback seek_callback,
1157   FLAC__StreamDecoderTellCallback tell_callback,
1158   FLAC__StreamDecoderLengthCallback length_callback,
1159   FLAC__StreamDecoderEofCallback eof_callback,
1160   FLAC__StreamDecoderWriteCallback write_callback,
1161   FLAC__StreamDecoderMetadataCallback metadata_callback,
1162   FLAC__StreamDecoderErrorCallback error_callback,
1163   void *client_data
1164);
1165
1166/** Initialize the decoder instance to decode native FLAC files.
1167 *
1168 *  This flavor of initialization sets up the decoder to decode from a
1169 *  plain native FLAC file.  For non-stdio streams, you must use
1170 *  FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
1171 *
1172 *  This function should be called after FLAC__stream_decoder_new() and
1173 *  FLAC__stream_decoder_set_*() but before any of the
1174 *  FLAC__stream_decoder_process_*() functions.  Will set and return the
1175 *  decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
1176 *  if initialization succeeded.
1177 *
1178 * \param  decoder            An uninitialized decoder instance.
1179 * \param  file               An open FLAC file.  The file should have been
1180 *                            opened with mode \c "rb" and rewound.  The file
1181 *                            becomes owned by the decoder and should not be
1182 *                            manipulated by the client while decoding.
1183 *                            Unless \a file is \c stdin, it will be closed
1184 *                            when FLAC__stream_decoder_finish() is called.
1185 *                            Note however that seeking will not work when
1186 *                            decoding from \c stdout since it is not seekable.
1187 * \param  write_callback     See FLAC__StreamDecoderWriteCallback.  This
1188 *                            pointer must not be \c NULL.
1189 * \param  metadata_callback  See FLAC__StreamDecoderMetadataCallback.  This
1190 *                            pointer may be \c NULL if the callback is not
1191 *                            desired.
1192 * \param  error_callback     See FLAC__StreamDecoderErrorCallback.  This
1193 *                            pointer must not be \c NULL.
1194 * \param  client_data        This value will be supplied to callbacks in their
1195 *                            \a client_data argument.
1196 * \assert
1197 *    \code decoder != NULL \endcode
1198 *    \code file != NULL \endcode
1199 * \retval FLAC__StreamDecoderInitStatus
1200 *    \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
1201 *    see FLAC__StreamDecoderInitStatus for the meanings of other return values.
1202 */
1203FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
1204   FLAC__StreamDecoder *decoder,
1205   FILE *file,
1206   FLAC__StreamDecoderWriteCallback write_callback,
1207   FLAC__StreamDecoderMetadataCallback metadata_callback,
1208   FLAC__StreamDecoderErrorCallback error_callback,
1209   void *client_data
1210);
1211
1212/** Initialize the decoder instance to decode Ogg FLAC files.
1213 *
1214 *  This flavor of initialization sets up the decoder to decode from a
1215 *  plain Ogg FLAC file.  For non-stdio streams, you must use
1216 *  FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
1217 *
1218 *  This function should be called after FLAC__stream_decoder_new() and
1219 *  FLAC__stream_decoder_set_*() but before any of the
1220 *  FLAC__stream_decoder_process_*() functions.  Will set and return the
1221 *  decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
1222 *  if initialization succeeded.
1223 *
1224 *  \note Support for Ogg FLAC in the library is optional.  If this
1225 *  library has been built without support for Ogg FLAC, this function
1226 *  will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
1227 *
1228 * \param  decoder            An uninitialized decoder instance.
1229 * \param  file               An open FLAC file.  The file should have been
1230 *                            opened with mode \c "rb" and rewound.  The file
1231 *                            becomes owned by the decoder and should not be
1232 *                            manipulated by the client while decoding.
1233 *                            Unless \a file is \c stdin, it will be closed
1234 *                            when FLAC__stream_decoder_finish() is called.
1235 *                            Note however that seeking will not work when
1236 *                            decoding from \c stdout since it is not seekable.
1237 * \param  write_callback     See FLAC__StreamDecoderWriteCallback.  This
1238 *                            pointer must not be \c NULL.
1239 * \param  metadata_callback  See FLAC__StreamDecoderMetadataCallback.  This
1240 *                            pointer may be \c NULL if the callback is not
1241 *                            desired.
1242 * \param  error_callback     See FLAC__StreamDecoderErrorCallback.  This
1243 *                            pointer must not be \c NULL.
1244 * \param  client_data        This value will be supplied to callbacks in their
1245 *                            \a client_data argument.
1246 * \assert
1247 *    \code decoder != NULL \endcode
1248 *    \code file != NULL \endcode
1249 * \retval FLAC__StreamDecoderInitStatus
1250 *    \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
1251 *    see FLAC__StreamDecoderInitStatus for the meanings of other return values.
1252 */
1253FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
1254   FLAC__StreamDecoder *decoder,
1255   FILE *file,
1256   FLAC__StreamDecoderWriteCallback write_callback,
1257   FLAC__StreamDecoderMetadataCallback metadata_callback,
1258   FLAC__StreamDecoderErrorCallback error_callback,
1259   void *client_data
1260);
1261
1262/** Initialize the decoder instance to decode native FLAC files.
1263 *
1264 *  This flavor of initialization sets up the decoder to decode from a plain
1265 *  native FLAC file.  If POSIX fopen() semantics are not sufficient, (for
1266 *  example, with Unicode filenames on Windows), you must use
1267 *  FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
1268 *  and provide callbacks for the I/O.
1269 *
1270 *  This function should be called after FLAC__stream_decoder_new() and
1271 *  FLAC__stream_decoder_set_*() but before any of the
1272 *  FLAC__stream_decoder_process_*() functions.  Will set and return the
1273 *  decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
1274 *  if initialization succeeded.
1275 *
1276 * \param  decoder            An uninitialized decoder instance.
1277 * \param  filename           The name of the file to decode from.  The file will
1278 *                            be opened with fopen().  Use \c NULL to decode from
1279 *                            \c stdin.  Note that \c stdin is not seekable.
1280 * \param  write_callback     See FLAC__StreamDecoderWriteCallback.  This
1281 *                            pointer must not be \c NULL.
1282 * \param  metadata_callback  See FLAC__StreamDecoderMetadataCallback.  This
1283 *                            pointer may be \c NULL if the callback is not
1284 *                            desired.
1285 * \param  error_callback     See FLAC__StreamDecoderErrorCallback.  This
1286 *                            pointer must not be \c NULL.
1287 * \param  client_data        This value will be supplied to callbacks in their
1288 *                            \a client_data argument.
1289 * \assert
1290 *    \code decoder != NULL \endcode
1291 * \retval FLAC__StreamDecoderInitStatus
1292 *    \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
1293 *    see FLAC__StreamDecoderInitStatus for the meanings of other return values.
1294 */
1295FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
1296   FLAC__StreamDecoder *decoder,
1297   const char *filename,
1298   FLAC__StreamDecoderWriteCallback write_callback,
1299   FLAC__StreamDecoderMetadataCallback metadata_callback,
1300   FLAC__StreamDecoderErrorCallback error_callback,
1301   void *client_data
1302);
1303
1304/** Initialize the decoder instance to decode Ogg FLAC files.
1305 *
1306 *  This flavor of initialization sets up the decoder to decode from a plain
1307 *  Ogg FLAC file.  If POSIX fopen() semantics are not sufficient, (for
1308 *  example, with Unicode filenames on Windows), you must use
1309 *  FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
1310 *  and provide callbacks for the I/O.
1311 *
1312 *  This function should be called after FLAC__stream_decoder_new() and
1313 *  FLAC__stream_decoder_set_*() but before any of the
1314 *  FLAC__stream_decoder_process_*() functions.  Will set and return the
1315 *  decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
1316 *  if initialization succeeded.
1317 *
1318 *  \note Support for Ogg FLAC in the library is optional.  If this
1319 *  library has been built without support for Ogg FLAC, this function
1320 *  will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
1321 *
1322 * \param  decoder            An uninitialized decoder instance.
1323 * \param  filename           The name of the file to decode from.  The file will
1324 *                            be opened with fopen().  Use \c NULL to decode from
1325 *                            \c stdin.  Note that \c stdin is not seekable.
1326 * \param  write_callback     See FLAC__StreamDecoderWriteCallback.  This
1327 *                            pointer must not be \c NULL.
1328 * \param  metadata_callback  See FLAC__StreamDecoderMetadataCallback.  This
1329 *                            pointer may be \c NULL if the callback is not
1330 *                            desired.
1331 * \param  error_callback     See FLAC__StreamDecoderErrorCallback.  This
1332 *                            pointer must not be \c NULL.
1333 * \param  client_data        This value will be supplied to callbacks in their
1334 *                            \a client_data argument.
1335 * \assert
1336 *    \code decoder != NULL \endcode
1337 * \retval FLAC__StreamDecoderInitStatus
1338 *    \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
1339 *    see FLAC__StreamDecoderInitStatus for the meanings of other return values.
1340 */
1341FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
1342   FLAC__StreamDecoder *decoder,
1343   const char *filename,
1344   FLAC__StreamDecoderWriteCallback write_callback,
1345   FLAC__StreamDecoderMetadataCallback metadata_callback,
1346   FLAC__StreamDecoderErrorCallback error_callback,
1347   void *client_data
1348);
1349
1350/** Finish the decoding process.
1351 *  Flushes the decoding buffer, releases resources, resets the decoder
1352 *  settings to their defaults, and returns the decoder state to
1353 *  FLAC__STREAM_DECODER_UNINITIALIZED.
1354 *
1355 *  In the event of a prematurely-terminated decode, it is not strictly
1356 *  necessary to call this immediately before FLAC__stream_decoder_delete()
1357 *  but it is good practice to match every FLAC__stream_decoder_init_*()
1358 *  with a FLAC__stream_decoder_finish().
1359 *
1360 * \param  decoder  An uninitialized decoder instance.
1361 * \assert
1362 *    \code decoder != NULL \endcode
1363 * \retval FLAC__bool
1364 *    \c false if MD5 checking is on AND a STREAMINFO block was available
1365 *    AND the MD5 signature in the STREAMINFO block was non-zero AND the
1366 *    signature does not match the one computed by the decoder; else
1367 *    \c true.
1368 */
1369FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
1370
1371/** Flush the stream input.
1372 *  The decoder's input buffer will be cleared and the state set to
1373 *  \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC.  This will also turn
1374 *  off MD5 checking.
1375 *
1376 * \param  decoder  A decoder instance.
1377 * \assert
1378 *    \code decoder != NULL \endcode
1379 * \retval FLAC__bool
1380 *    \c true if successful, else \c false if a memory allocation
1381 *    error occurs (in which case the state will be set to
1382 *    \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
1383 */
1384FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
1385
1386/** Reset the decoding process.
1387 *  The decoder's input buffer will be cleared and the state set to
1388 *  \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA.  This is similar to
1389 *  FLAC__stream_decoder_finish() except that the settings are
1390 *  preserved; there is no need to call FLAC__stream_decoder_init_*()
1391 *  before decoding again.  MD5 checking will be restored to its original
1392 *  setting.
1393 *
1394 *  If the decoder is seekable, or was initialized with
1395 *  FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
1396 *  the decoder will also attempt to seek to the beginning of the file.
1397 *  If this rewind fails, this function will return \c false.  It follows
1398 *  that FLAC__stream_decoder_reset() cannot be used when decoding from
1399 *  \c stdin.
1400 *
1401 *  If the decoder was initialized with FLAC__stream_encoder_init*_stream()
1402 *  and is not seekable (i.e. no seek callback was provided or the seek
1403 *  callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
1404 *  is the duty of the client to start feeding data from the beginning of
1405 *  the stream on the next FLAC__stream_decoder_process() or
1406 *  FLAC__stream_decoder_process_interleaved() call.
1407 *
1408 * \param  decoder  A decoder instance.
1409 * \assert
1410 *    \code decoder != NULL \endcode
1411 * \retval FLAC__bool
1412 *    \c true if successful, else \c false if a memory allocation occurs
1413 *    (in which case the state will be set to
1414 *    \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
1415 *    occurs (the state will be unchanged).
1416 */
1417FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
1418
1419/** Decode one metadata block or audio frame.
1420 *  This version instructs the decoder to decode a either a single metadata
1421 *  block or a single frame and stop, unless the callbacks return a fatal
1422 *  error or the read callback returns
1423 *  \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
1424 *
1425 *  As the decoder needs more input it will call the read callback.
1426 *  Depending on what was decoded, the metadata or write callback will be
1427 *  called with the decoded metadata block or audio frame.
1428 *
1429 *  Unless there is a fatal read error or end of stream, this function
1430 *  will return once one whole frame is decoded.  In other words, if the
1431 *  stream is not synchronized or points to a corrupt frame header, the
1432 *  decoder will continue to try and resync until it gets to a valid
1433 *  frame, then decode one frame, then return.  If the decoder points to
1434 *  a frame whose frame CRC in the frame footer does not match the
1435 *  computed frame CRC, this function will issue a
1436 *  FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
1437 *  error callback, and return, having decoded one complete, although
1438 *  corrupt, frame.  (Such corrupted frames are sent as silence of the
1439 *  correct length to the write callback.)
1440 *
1441 * \param  decoder  An initialized decoder instance.
1442 * \assert
1443 *    \code decoder != NULL \endcode
1444 * \retval FLAC__bool
1445 *    \c false if any fatal read, write, or memory allocation error
1446 *    occurred (meaning decoding must stop), else \c true; for more
1447 *    information about the decoder, check the decoder state with
1448 *    FLAC__stream_decoder_get_state().
1449 */
1450FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
1451
1452/** Decode until the end of the metadata.
1453 *  This version instructs the decoder to decode from the current position
1454 *  and continue until all the metadata has been read, or until the
1455 *  callbacks return a fatal error or the read callback returns
1456 *  \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
1457 *
1458 *  As the decoder needs more input it will call the read callback.
1459 *  As each metadata block is decoded, the metadata callback will be called
1460 *  with the decoded metadata.
1461 *
1462 * \param  decoder  An initialized decoder instance.
1463 * \assert
1464 *    \code decoder != NULL \endcode
1465 * \retval FLAC__bool
1466 *    \c false if any fatal read, write, or memory allocation error
1467 *    occurred (meaning decoding must stop), else \c true; for more
1468 *    information about the decoder, check the decoder state with
1469 *    FLAC__stream_decoder_get_state().
1470 */
1471FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
1472
1473/** Decode until the end of the stream.
1474 *  This version instructs the decoder to decode from the current position
1475 *  and continue until the end of stream (the read callback returns
1476 *  \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
1477 *  callbacks return a fatal error.
1478 *
1479 *  As the decoder needs more input it will call the read callback.
1480 *  As each metadata block and frame is decoded, the metadata or write
1481 *  callback will be called with the decoded metadata or frame.
1482 *
1483 * \param  decoder  An initialized decoder instance.
1484 * \assert
1485 *    \code decoder != NULL \endcode
1486 * \retval FLAC__bool
1487 *    \c false if any fatal read, write, or memory allocation error
1488 *    occurred (meaning decoding must stop), else \c true; for more
1489 *    information about the decoder, check the decoder state with
1490 *    FLAC__stream_decoder_get_state().
1491 */
1492FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
1493
1494/** Skip one audio frame.
1495 *  This version instructs the decoder to 'skip' a single frame and stop,
1496 *  unless the callbacks return a fatal error or the read callback returns
1497 *  \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
1498 *
1499 *  The decoding flow is the same as what occurs when
1500 *  FLAC__stream_decoder_process_single() is called to process an audio
1501 *  frame, except that this function does not decode the parsed data into
1502 *  PCM or call the write callback.  The integrity of the frame is still
1503 *  checked the same way as in the other process functions.
1504 *
1505 *  This function will return once one whole frame is skipped, in the
1506 *  same way that FLAC__stream_decoder_process_single() will return once
1507 *  one whole frame is decoded.
1508 *
1509 *  This function can be used in more quickly determining FLAC frame
1510 *  boundaries when decoding of the actual data is not needed, for
1511 *  example when an application is separating a FLAC stream into frames
1512 *  for editing or storing in a container.  To do this, the application
1513 *  can use FLAC__stream_decoder_skip_single_frame() to quickly advance
1514 *  to the next frame, then use
1515 *  FLAC__stream_decoder_get_decode_position() to find the new frame
1516 *  boundary.
1517 *
1518 *  This function should only be called when the stream has advanced
1519 *  past all the metadata, otherwise it will return \c false.
1520 *
1521 * \param  decoder  An initialized decoder instance not in a metadata
1522 *                  state.
1523 * \assert
1524 *    \code decoder != NULL \endcode
1525 * \retval FLAC__bool
1526 *    \c false if any fatal read, write, or memory allocation error
1527 *    occurred (meaning decoding must stop), or if the decoder
1528 *    is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
1529 *    FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
1530 *    information about the decoder, check the decoder state with
1531 *    FLAC__stream_decoder_get_state().
1532 */
1533FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
1534
1535/** Flush the input and seek to an absolute sample.
1536 *  Decoding will resume at the given sample.  Note that because of
1537 *  this, the next write callback may contain a partial block.  The
1538 *  client must support seeking the input or this function will fail
1539 *  and return \c false.  Furthermore, if the decoder state is
1540 *  \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
1541 *  with FLAC__stream_decoder_flush() or reset with
1542 *  FLAC__stream_decoder_reset() before decoding can continue.
1543 *
1544 * \param  decoder  A decoder instance.
1545 * \param  sample   The target sample number to seek to.
1546 * \assert
1547 *    \code decoder != NULL \endcode
1548 * \retval FLAC__bool
1549 *    \c true if successful, else \c false.
1550 */
1551FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
1552
1553/* \} */
1554
1555#ifdef __cplusplus
1556}
1557#endif
1558
1559#endif
src/lib/libflac/include/flac/assert.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__ASSERT_H
33#define FLAC__ASSERT_H
34
35/* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
36#ifdef DEBUG
37#include <assert.h>
38#define FLAC__ASSERT(x) assert(x)
39#define FLAC__ASSERT_DECLARATION(x) x
40#else
41#define FLAC__ASSERT(x)
42#define FLAC__ASSERT_DECLARATION(x)
43#endif
44
45#endif
src/lib/libflac/include/flac/export.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__EXPORT_H
33#define FLAC__EXPORT_H
34
35/** \file include/FLAC/export.h
36 *
37 *  \brief
38 *  This module contains #defines and symbols for exporting function
39 *  calls, and providing version information and compiled-in features.
40 *
41 *  See the \link flac_export export \endlink module.
42 */
43
44/** \defgroup flac_export FLAC/export.h: export symbols
45 *  \ingroup flac
46 *
47 *  \brief
48 *  This module contains #defines and symbols for exporting function
49 *  calls, and providing version information and compiled-in features.
50 *
51 *  If you are compiling with MSVC and will link to the static library
52 *  (libFLAC.lib) you should define FLAC__NO_DLL in your project to
53 *  make sure the symbols are exported properly.
54 *
55 * \{
56 */
57
58#if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
59#define FLAC_API
60
61#else
62
63#ifdef FLAC_API_EXPORTS
64#define   FLAC_API   _declspec(dllexport)
65#else
66#define FLAC_API   _declspec(dllimport)
67
68#endif
69#endif
70
71/** These #defines will mirror the libtool-based library version number, see
72 * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
73 */
74#define FLAC_API_VERSION_CURRENT 10
75#define FLAC_API_VERSION_REVISION 0 /**< see above */
76#define FLAC_API_VERSION_AGE 2 /**< see above */
77
78#ifdef __cplusplus
79extern "C" {
80#endif
81
82/** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
83extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
84
85#ifdef __cplusplus
86}
87#endif
88
89/* \} */
90
91#endif
src/lib/libflac/include/flac/all.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__ALL_H
33#define FLAC__ALL_H
34
35#include "export.h"
36
37#include "assert.h"
38#include "callback.h"
39#include "format.h"
40#include "metadata.h"
41#include "ordinals.h"
42#include "stream_decoder.h"
43#include "stream_encoder.h"
44
45/** \mainpage
46 *
47 * \section intro Introduction
48 *
49 * This is the documentation for the FLAC C and C++ APIs.  It is
50 * highly interconnected; this introduction should give you a top
51 * level idea of the structure and how to find the information you
52 * need.  As a prerequisite you should have at least a basic
53 * knowledge of the FLAC format, documented
54 * <A HREF="../format.html">here</A>.
55 *
56 * \section c_api FLAC C API
57 *
58 * The FLAC C API is the interface to libFLAC, a set of structures
59 * describing the components of FLAC streams, and functions for
60 * encoding and decoding streams, as well as manipulating FLAC
61 * metadata in files.  The public include files will be installed
62 * in your include area (for example /usr/include/FLAC/...).
63 *
64 * By writing a little code and linking against libFLAC, it is
65 * relatively easy to add FLAC support to another program.  The
66 * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
67 * Complete source code of libFLAC as well as the command-line
68 * encoder and plugins is available and is a useful source of
69 * examples.
70 *
71 * Aside from encoders and decoders, libFLAC provides a powerful
72 * metadata interface for manipulating metadata in FLAC files.  It
73 * allows the user to add, delete, and modify FLAC metadata blocks
74 * and it can automatically take advantage of PADDING blocks to avoid
75 * rewriting the entire FLAC file when changing the size of the
76 * metadata.
77 *
78 * libFLAC usually only requires the standard C library and C math
79 * library. In particular, threading is not used so there is no
80 * dependency on a thread library. However, libFLAC does not use
81 * global variables and should be thread-safe.
82 *
83 * libFLAC also supports encoding to and decoding from Ogg FLAC.
84 * However the metadata editing interfaces currently have limited
85 * read-only support for Ogg FLAC files.
86 *
87 * \section cpp_api FLAC C++ API
88 *
89 * The FLAC C++ API is a set of classes that encapsulate the
90 * structures and functions in libFLAC.  They provide slightly more
91 * functionality with respect to metadata but are otherwise
92 * equivalent.  For the most part, they share the same usage as
93 * their counterparts in libFLAC, and the FLAC C API documentation
94 * can be used as a supplement.  The public include files
95 * for the C++ API will be installed in your include area (for
96 * example /usr/include/FLAC++/...).
97 *
98 * libFLAC++ is also licensed under
99 * <A HREF="../license.html">Xiph's BSD license</A>.
100 *
101 * \section getting_started Getting Started
102 *
103 * A good starting point for learning the API is to browse through
104 * the <A HREF="modules.html">modules</A>.  Modules are logical
105 * groupings of related functions or classes, which correspond roughly
106 * to header files or sections of header files.  Each module includes a
107 * detailed description of the general usage of its functions or
108 * classes.
109 *
110 * From there you can go on to look at the documentation of
111 * individual functions.  You can see different views of the individual
112 * functions through the links in top bar across this page.
113 *
114 * If you prefer a more hands-on approach, you can jump right to some
115 * <A HREF="../documentation_example_code.html">example code</A>.
116 *
117 * \section porting_guide Porting Guide
118 *
119 * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
120 * has been introduced which gives detailed instructions on how to
121 * port your code to newer versions of FLAC.
122 *
123 * \section embedded_developers Embedded Developers
124 *
125 * libFLAC has grown larger over time as more functionality has been
126 * included, but much of it may be unnecessary for a particular embedded
127 * implementation.  Unused parts may be pruned by some simple editing of
128 * src/libFLAC/Makefile.am.  In general, the decoders, encoders, and
129 * metadata interface are all independent from each other.
130 *
131 * It is easiest to just describe the dependencies:
132 *
133 * - All modules depend on the \link flac_format Format \endlink module.
134 * - The decoders and encoders depend on the bitbuffer.
135 * - The decoder is independent of the encoder.  The encoder uses the
136 *   decoder because of the verify feature, but this can be removed if
137 *   not needed.
138 * - Parts of the metadata interface require the stream decoder (but not
139 *   the encoder).
140 * - Ogg support is selectable through the compile time macro
141 *   \c FLAC__HAS_OGG.
142 *
143 * For example, if your application only requires the stream decoder, no
144 * encoder, and no metadata interface, you can remove the stream encoder
145 * and the metadata interface, which will greatly reduce the size of the
146 * library.
147 *
148 * Also, there are several places in the libFLAC code with comments marked
149 * with "OPT:" where a #define can be changed to enable code that might be
150 * faster on a specific platform.  Experimenting with these can yield faster
151 * binaries.
152 */
153
154/** \defgroup porting Porting Guide for New Versions
155 *
156 * This module describes differences in the library interfaces from
157 * version to version.  It assists in the porting of code that uses
158 * the libraries to newer versions of FLAC.
159 *
160 * One simple facility for making porting easier that has been added
161 * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
162 * library's includes (e.g. \c include/FLAC/export.h).  The
163 * \c #defines mirror the libraries'
164 * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
165 * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
166 * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
167 * These can be used to support multiple versions of an API during the
168 * transition phase, e.g.
169 *
170 * \code
171 * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
172 *   legacy code
173 * #else
174 *   new code
175 * #endif
176 * \endcode
177 *
178 * The the source will work for multiple versions and the legacy code can
179 * easily be removed when the transition is complete.
180 *
181 * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
182 * include/FLAC/export.h), which can be used to determine whether or not
183 * the library has been compiled with support for Ogg FLAC.  This is
184 * simpler than trying to call an Ogg init function and catching the
185 * error.
186 */
187
188/** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
189 *  \ingroup porting
190 *
191 *  \brief
192 *  This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
193 *
194 * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
195 * been simplified.  First, libOggFLAC has been merged into libFLAC and
196 * libOggFLAC++ has been merged into libFLAC++.  Second, both the three
197 * decoding layers and three encoding layers have been merged into a
198 * single stream decoder and stream encoder.  That is, the functionality
199 * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
200 * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
201 * FLAC__FileEncoder into FLAC__StreamEncoder.  Only the
202 * FLAC__StreamDecoder and FLAC__StreamEncoder remain.  What this means
203 * is there is now a single API that can be used to encode or decode
204 * streams to/from native FLAC or Ogg FLAC and the single API can work
205 * on both seekable and non-seekable streams.
206 *
207 * Instead of creating an encoder or decoder of a certain layer, now the
208 * client will always create a FLAC__StreamEncoder or
209 * FLAC__StreamDecoder.  The old layers are now differentiated by the
210 * initialization function.  For example, for the decoder,
211 * FLAC__stream_decoder_init() has been replaced by
212 * FLAC__stream_decoder_init_stream().  This init function takes
213 * callbacks for the I/O, and the seeking callbacks are optional.  This
214 * allows the client to use the same object for seekable and
215 * non-seekable streams.  For decoding a FLAC file directly, the client
216 * can use FLAC__stream_decoder_init_file() and pass just a filename
217 * and fewer callbacks; most of the other callbacks are supplied
218 * internally.  For situations where fopen()ing by filename is not
219 * possible (e.g. Unicode filenames on Windows) the client can instead
220 * open the file itself and supply the FILE* to
221 * FLAC__stream_decoder_init_FILE().  The init functions now returns a
222 * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
223 * Since the callbacks and client data are now passed to the init
224 * function, the FLAC__stream_decoder_set_*_callback() functions and
225 * FLAC__stream_decoder_set_client_data() are no longer needed.  The
226 * rest of the calls to the decoder are the same as before.
227 *
228 * There are counterpart init functions for Ogg FLAC, e.g.
229 * FLAC__stream_decoder_init_ogg_stream().  All the rest of the calls
230 * and callbacks are the same as for native FLAC.
231 *
232 * As an example, in FLAC 1.1.2 a seekable stream decoder would have
233 * been set up like so:
234 *
235 * \code
236 * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
237 * if(decoder == NULL) do_something;
238 * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
239 * [... other settings ...]
240 * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
241 * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
242 * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
243 * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
244 * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
245 * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
246 * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
247 * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
248 * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
249 * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
250 * \endcode
251 *
252 * In FLAC 1.1.3 it is like this:
253 *
254 * \code
255 * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
256 * if(decoder == NULL) do_something;
257 * FLAC__stream_decoder_set_md5_checking(decoder, true);
258 * [... other settings ...]
259 * if(FLAC__stream_decoder_init_stream(
260 *   decoder,
261 *   my_read_callback,
262 *   my_seek_callback,      // or NULL
263 *   my_tell_callback,      // or NULL
264 *   my_length_callback,    // or NULL
265 *   my_eof_callback,       // or NULL
266 *   my_write_callback,
267 *   my_metadata_callback,  // or NULL
268 *   my_error_callback,
269 *   my_client_data
270 * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
271 * \endcode
272 *
273 * or you could do;
274 *
275 * \code
276 * [...]
277 * FILE *file = fopen("somefile.flac","rb");
278 * if(file == NULL) do_somthing;
279 * if(FLAC__stream_decoder_init_FILE(
280 *   decoder,
281 *   file,
282 *   my_write_callback,
283 *   my_metadata_callback,  // or NULL
284 *   my_error_callback,
285 *   my_client_data
286 * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
287 * \endcode
288 *
289 * or just:
290 *
291 * \code
292 * [...]
293 * if(FLAC__stream_decoder_init_file(
294 *   decoder,
295 *   "somefile.flac",
296 *   my_write_callback,
297 *   my_metadata_callback,  // or NULL
298 *   my_error_callback,
299 *   my_client_data
300 * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
301 * \endcode
302 *
303 * Another small change to the decoder is in how it handles unparseable
304 * streams.  Before, when the decoder found an unparseable stream
305 * (reserved for when the decoder encounters a stream from a future
306 * encoder that it can't parse), it changed the state to
307 * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM.  Now the decoder instead
308 * drops sync and calls the error callback with a new error code
309 * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM.  This is
310 * more robust.  If your error callback does not discriminate on the the
311 * error state, your code does not need to be changed.
312 *
313 * The encoder now has a new setting:
314 * FLAC__stream_encoder_set_apodization().  This is for setting the
315 * method used to window the data before LPC analysis.  You only need to
316 * add a call to this function if the default is not suitable.   There
317 * are also two new convenience functions that may be useful:
318 * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
319 * FLAC__metadata_get_cuesheet().
320 *
321 * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
322 * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
323 * is now \c size_t instead of \c unsigned.
324 */
325
326/** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
327 *  \ingroup porting
328 *
329 *  \brief
330 *  This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
331 *
332 * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
333 * There was a slight change in the implementation of
334 * FLAC__stream_encoder_set_metadata(); the function now makes a copy
335 * of the \a metadata array of pointers so the client no longer needs
336 * to maintain it after the call.  The objects themselves that are
337 * pointed to by the array are still not copied though and must be
338 * maintained until the call to FLAC__stream_encoder_finish().
339 */
340
341/** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
342 *  \ingroup porting
343 *
344 *  \brief
345 *  This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
346 *
347 * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
348 * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
349 * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
350 *
351 * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
352 * has changed to reflect the conversion of one of the reserved bits
353 * into active use.  It used to be \c 2 and now is \c 1.  However the
354 * FLAC frame header length has not changed, so to skip the proper
355 * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
356 * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
357 */
358
359/** \defgroup flac FLAC C API
360 *
361 * The FLAC C API is the interface to libFLAC, a set of structures
362 * describing the components of FLAC streams, and functions for
363 * encoding and decoding streams, as well as manipulating FLAC
364 * metadata in files.
365 *
366 * You should start with the format components as all other modules
367 * are dependent on it.
368 */
369
370#endif
src/lib/libflac/include/flac/format.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__FORMAT_H
33#define FLAC__FORMAT_H
34
35#include "export.h"
36#include "ordinals.h"
37
38#ifdef __cplusplus
39extern "C" {
40#endif
41
42/** \file include/FLAC/format.h
43 *
44 *  \brief
45 *  This module contains structure definitions for the representation
46 *  of FLAC format components in memory.  These are the basic
47 *  structures used by the rest of the interfaces.
48 *
49 *  See the detailed documentation in the
50 *  \link flac_format format \endlink module.
51 */
52
53/** \defgroup flac_format FLAC/format.h: format components
54 *  \ingroup flac
55 *
56 *  \brief
57 *  This module contains structure definitions for the representation
58 *  of FLAC format components in memory.  These are the basic
59 *  structures used by the rest of the interfaces.
60 *
61 *  First, you should be familiar with the
62 *  <A HREF="../format.html">FLAC format</A>.  Many of the values here
63 *  follow directly from the specification.  As a user of libFLAC, the
64 *  interesting parts really are the structures that describe the frame
65 *  header and metadata blocks.
66 *
67 *  The format structures here are very primitive, designed to store
68 *  information in an efficient way.  Reading information from the
69 *  structures is easy but creating or modifying them directly is
70 *  more complex.  For the most part, as a user of a library, editing
71 *  is not necessary; however, for metadata blocks it is, so there are
72 *  convenience functions provided in the \link flac_metadata metadata
73 *  module \endlink to simplify the manipulation of metadata blocks.
74 *
75 * \note
76 * It's not the best convention, but symbols ending in _LEN are in bits
77 * and _LENGTH are in bytes.  _LENGTH symbols are \#defines instead of
78 * global variables because they are usually used when declaring byte
79 * arrays and some compilers require compile-time knowledge of array
80 * sizes when declared on the stack.
81 *
82 * \{
83 */
84
85
86/*
87   Most of the values described in this file are defined by the FLAC
88   format specification.  There is nothing to tune here.
89*/
90
91/** The largest legal metadata type code. */
92#define FLAC__MAX_METADATA_TYPE_CODE (126u)
93
94/** The minimum block size, in samples, permitted by the format. */
95#define FLAC__MIN_BLOCK_SIZE (16u)
96
97/** The maximum block size, in samples, permitted by the format. */
98#define FLAC__MAX_BLOCK_SIZE (65535u)
99
100/** The maximum block size, in samples, permitted by the FLAC subset for
101 *  sample rates up to 48kHz. */
102#define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
103
104/** The maximum number of channels permitted by the format. */
105#define FLAC__MAX_CHANNELS (8u)
106
107/** The minimum sample resolution permitted by the format. */
108#define FLAC__MIN_BITS_PER_SAMPLE (4u)
109
110/** The maximum sample resolution permitted by the format. */
111#define FLAC__MAX_BITS_PER_SAMPLE (32u)
112
113/** The maximum sample resolution permitted by libFLAC.
114 *
115 * \warning
116 * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format.  However,
117 * the reference encoder/decoder is currently limited to 24 bits because
118 * of prevalent 32-bit math, so make sure and use this value when
119 * appropriate.
120 */
121#define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
122
123/** The maximum sample rate permitted by the format.  The value is
124 *  ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
125 *  as to why.
126 */
127#define FLAC__MAX_SAMPLE_RATE (655350u)
128
129/** The maximum LPC order permitted by the format. */
130#define FLAC__MAX_LPC_ORDER (32u)
131
132/** The maximum LPC order permitted by the FLAC subset for sample rates
133 *  up to 48kHz. */
134#define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
135
136/** The minimum quantized linear predictor coefficient precision
137 *  permitted by the format.
138 */
139#define FLAC__MIN_QLP_COEFF_PRECISION (5u)
140
141/** The maximum quantized linear predictor coefficient precision
142 *  permitted by the format.
143 */
144#define FLAC__MAX_QLP_COEFF_PRECISION (15u)
145
146/** The maximum order of the fixed predictors permitted by the format. */
147#define FLAC__MAX_FIXED_ORDER (4u)
148
149/** The maximum Rice partition order permitted by the format. */
150#define FLAC__MAX_RICE_PARTITION_ORDER (15u)
151
152/** The maximum Rice partition order permitted by the FLAC Subset. */
153#define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
154
155/** The version string of the release, stamped onto the libraries and binaries.
156 *
157 * \note
158 * This does not correspond to the shared library version number, which
159 * is used to determine binary compatibility.
160 */
161extern FLAC_API const char *FLAC__VERSION_STRING;
162
163/** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
164 *  This is a NUL-terminated ASCII string; when inserted into the
165 *  VORBIS_COMMENT the trailing null is stripped.
166 */
167extern FLAC_API const char *FLAC__VENDOR_STRING;
168
169/** The byte string representation of the beginning of a FLAC stream. */
170extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
171
172/** The 32-bit integer big-endian representation of the beginning of
173 *  a FLAC stream.
174 */
175extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
176
177/** The length of the FLAC signature in bits. */
178extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
179
180/** The length of the FLAC signature in bytes. */
181#define FLAC__STREAM_SYNC_LENGTH (4u)
182
183
184/*****************************************************************************
185 *
186 * Subframe structures
187 *
188 *****************************************************************************/
189
190/*****************************************************************************/
191
192/** An enumeration of the available entropy coding methods. */
193typedef enum {
194   FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
195   /**< Residual is coded by partitioning into contexts, each with it's own
196    * 4-bit Rice parameter. */
197
198   FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
199   /**< Residual is coded by partitioning into contexts, each with it's own
200    * 5-bit Rice parameter. */
201} FLAC__EntropyCodingMethodType;
202
203/** Maps a FLAC__EntropyCodingMethodType to a C string.
204 *
205 *  Using a FLAC__EntropyCodingMethodType as the index to this array will
206 *  give the string equivalent.  The contents should not be modified.
207 */
208extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
209
210
211/** Contents of a Rice partitioned residual
212 */
213typedef struct {
214
215   unsigned *parameters;
216   /**< The Rice parameters for each context. */
217
218   unsigned *raw_bits;
219   /**< Widths for escape-coded partitions.  Will be non-zero for escaped
220    * partitions and zero for unescaped partitions.
221    */
222
223   unsigned capacity_by_order;
224   /**< The capacity of the \a parameters and \a raw_bits arrays
225    * specified as an order, i.e. the number of array elements
226    * allocated is 2 ^ \a capacity_by_order.
227    */
228} FLAC__EntropyCodingMethod_PartitionedRiceContents;
229
230/** Header for a Rice partitioned residual.  (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
231 */
232typedef struct {
233
234   unsigned order;
235   /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
236
237   const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
238   /**< The context's Rice parameters and/or raw bits. */
239
240} FLAC__EntropyCodingMethod_PartitionedRice;
241
242extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
243extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
244extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
245extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
246
247extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
248/**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
249extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
250/**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
251
252/** Header for the entropy coding method.  (c.f. <A HREF="../format.html#residual">format specification</A>)
253 */
254typedef struct {
255   FLAC__EntropyCodingMethodType type;
256   union {
257      FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
258   } data;
259} FLAC__EntropyCodingMethod;
260
261extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
262
263/*****************************************************************************/
264
265/** An enumeration of the available subframe types. */
266typedef enum {
267   FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
268   FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
269   FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
270   FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
271} FLAC__SubframeType;
272
273/** Maps a FLAC__SubframeType to a C string.
274 *
275 *  Using a FLAC__SubframeType as the index to this array will
276 *  give the string equivalent.  The contents should not be modified.
277 */
278extern FLAC_API const char * const FLAC__SubframeTypeString[];
279
280
281/** CONSTANT subframe.  (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
282 */
283typedef struct {
284   FLAC__int32 value; /**< The constant signal value. */
285} FLAC__Subframe_Constant;
286
287
288/** VERBATIM subframe.  (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
289 */
290typedef struct {
291   const FLAC__int32 *data; /**< A pointer to verbatim signal. */
292} FLAC__Subframe_Verbatim;
293
294
295/** FIXED subframe.  (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
296 */
297typedef struct {
298   FLAC__EntropyCodingMethod entropy_coding_method;
299   /**< The residual coding method. */
300
301   unsigned order;
302   /**< The polynomial order. */
303
304   FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
305   /**< Warmup samples to prime the predictor, length == order. */
306
307   const FLAC__int32 *residual;
308   /**< The residual signal, length == (blocksize minus order) samples. */
309} FLAC__Subframe_Fixed;
310
311
312/** LPC subframe.  (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
313 */
314typedef struct {
315   FLAC__EntropyCodingMethod entropy_coding_method;
316   /**< The residual coding method. */
317
318   unsigned order;
319   /**< The FIR order. */
320
321   unsigned qlp_coeff_precision;
322   /**< Quantized FIR filter coefficient precision in bits. */
323
324   int quantization_level;
325   /**< The qlp coeff shift needed. */
326
327   FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
328   /**< FIR filter coefficients. */
329
330   FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
331   /**< Warmup samples to prime the predictor, length == order. */
332
333   const FLAC__int32 *residual;
334   /**< The residual signal, length == (blocksize minus order) samples. */
335} FLAC__Subframe_LPC;
336
337extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
338extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
339
340
341/** FLAC subframe structure.  (c.f. <A HREF="../format.html#subframe">format specification</A>)
342 */
343typedef struct {
344   FLAC__SubframeType type;
345   union {
346      FLAC__Subframe_Constant constant;
347      FLAC__Subframe_Fixed fixed;
348      FLAC__Subframe_LPC lpc;
349      FLAC__Subframe_Verbatim verbatim;
350   } data;
351   unsigned wasted_bits;
352} FLAC__Subframe;
353
354/** == 1 (bit)
355 *
356 * This used to be a zero-padding bit (hence the name
357 * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit.  It still has a
358 * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
359 * to mean something else.
360 */
361extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
362extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
363extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
364
365extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
366extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
367extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
368extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
369
370/*****************************************************************************/
371
372
373/*****************************************************************************
374 *
375 * Frame structures
376 *
377 *****************************************************************************/
378
379/** An enumeration of the available channel assignments. */
380typedef enum {
381   FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
382   FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
383   FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
384   FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
385} FLAC__ChannelAssignment;
386
387/** Maps a FLAC__ChannelAssignment to a C string.
388 *
389 *  Using a FLAC__ChannelAssignment as the index to this array will
390 *  give the string equivalent.  The contents should not be modified.
391 */
392extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
393
394/** An enumeration of the possible frame numbering methods. */
395typedef enum {
396   FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
397   FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
398} FLAC__FrameNumberType;
399
400/** Maps a FLAC__FrameNumberType to a C string.
401 *
402 *  Using a FLAC__FrameNumberType as the index to this array will
403 *  give the string equivalent.  The contents should not be modified.
404 */
405extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
406
407
408/** FLAC frame header structure.  (c.f. <A HREF="../format.html#frame_header">format specification</A>)
409 */
410typedef struct {
411   unsigned blocksize;
412   /**< The number of samples per subframe. */
413
414   unsigned sample_rate;
415   /**< The sample rate in Hz. */
416
417   unsigned channels;
418   /**< The number of channels (== number of subframes). */
419
420   FLAC__ChannelAssignment channel_assignment;
421   /**< The channel assignment for the frame. */
422
423   unsigned bits_per_sample;
424   /**< The sample resolution. */
425
426   FLAC__FrameNumberType number_type;
427   /**< The numbering scheme used for the frame.  As a convenience, the
428    * decoder will always convert a frame number to a sample number because
429    * the rules are complex. */
430
431   union {
432      FLAC__uint32 frame_number;
433      FLAC__uint64 sample_number;
434   } number;
435   /**< The frame number or sample number of first sample in frame;
436    * use the \a number_type value to determine which to use. */
437
438   FLAC__uint8 crc;
439   /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
440    * of the raw frame header bytes, meaning everything before the CRC byte
441    * including the sync code.
442    */
443} FLAC__FrameHeader;
444
445extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
446extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
447extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
448extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
449extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
450extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
451extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
452extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
453extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
454extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
455
456
457/** FLAC frame footer structure.  (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
458 */
459typedef struct {
460   FLAC__uint16 crc;
461   /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
462    * 0) of the bytes before the crc, back to and including the frame header
463    * sync code.
464    */
465} FLAC__FrameFooter;
466
467extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
468
469
470/** FLAC frame structure.  (c.f. <A HREF="../format.html#frame">format specification</A>)
471 */
472typedef struct {
473   FLAC__FrameHeader header;
474   FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
475   FLAC__FrameFooter footer;
476} FLAC__Frame;
477
478/*****************************************************************************/
479
480
481/*****************************************************************************
482 *
483 * Meta-data structures
484 *
485 *****************************************************************************/
486
487/** An enumeration of the available metadata block types. */
488typedef enum {
489
490   FLAC__METADATA_TYPE_STREAMINFO = 0,
491   /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
492
493   FLAC__METADATA_TYPE_PADDING = 1,
494   /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
495
496   FLAC__METADATA_TYPE_APPLICATION = 2,
497   /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
498
499   FLAC__METADATA_TYPE_SEEKTABLE = 3,
500   /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
501
502   FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
503   /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
504
505   FLAC__METADATA_TYPE_CUESHEET = 5,
506   /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
507
508   FLAC__METADATA_TYPE_PICTURE = 6,
509   /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
510
511   FLAC__METADATA_TYPE_UNDEFINED = 7
512   /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
513
514} FLAC__MetadataType;
515
516/** Maps a FLAC__MetadataType to a C string.
517 *
518 *  Using a FLAC__MetadataType as the index to this array will
519 *  give the string equivalent.  The contents should not be modified.
520 */
521extern FLAC_API const char * const FLAC__MetadataTypeString[];
522
523
524/** FLAC STREAMINFO structure.  (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
525 */
526typedef struct {
527   unsigned min_blocksize, max_blocksize;
528   unsigned min_framesize, max_framesize;
529   unsigned sample_rate;
530   unsigned channels;
531   unsigned bits_per_sample;
532   FLAC__uint64 total_samples;
533   FLAC__byte md5sum[16];
534} FLAC__StreamMetadata_StreamInfo;
535
536extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
537extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
538extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
539extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
540extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
541extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
542extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
543extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
544extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
545
546/** The total stream length of the STREAMINFO block in bytes. */
547#define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
548
549/** FLAC PADDING structure.  (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
550 */
551typedef struct {
552   int dummy;
553   /**< Conceptually this is an empty struct since we don't store the
554    * padding bytes.  Empty structs are not allowed by some C compilers,
555    * hence the dummy.
556    */
557} FLAC__StreamMetadata_Padding;
558
559
560/** FLAC APPLICATION structure.  (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
561 */
562typedef struct {
563   FLAC__byte id[4];
564   FLAC__byte *data;
565} FLAC__StreamMetadata_Application;
566
567extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
568
569/** SeekPoint structure used in SEEKTABLE blocks.  (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
570 */
571typedef struct {
572   FLAC__uint64 sample_number;
573   /**<  The sample number of the target frame. */
574
575   FLAC__uint64 stream_offset;
576   /**< The offset, in bytes, of the target frame with respect to
577    * beginning of the first frame. */
578
579   unsigned frame_samples;
580   /**< The number of samples in the target frame. */
581} FLAC__StreamMetadata_SeekPoint;
582
583extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
584extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
585extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
586
587/** The total stream length of a seek point in bytes. */
588#define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
589
590/** The value used in the \a sample_number field of
591 *  FLAC__StreamMetadataSeekPoint used to indicate a placeholder
592 *  point (== 0xffffffffffffffff).
593 */
594extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
595
596
597/** FLAC SEEKTABLE structure.  (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
598 *
599 * \note From the format specification:
600 * - The seek points must be sorted by ascending sample number.
601 * - Each seek point's sample number must be the first sample of the
602 *   target frame.
603 * - Each seek point's sample number must be unique within the table.
604 * - Existence of a SEEKTABLE block implies a correct setting of
605 *   total_samples in the stream_info block.
606 * - Behavior is undefined when more than one SEEKTABLE block is
607 *   present in a stream.
608 */
609typedef struct {
610   unsigned num_points;
611   FLAC__StreamMetadata_SeekPoint *points;
612} FLAC__StreamMetadata_SeekTable;
613
614
615/** Vorbis comment entry structure used in VORBIS_COMMENT blocks.  (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
616 *
617 *  For convenience, the APIs maintain a trailing NUL character at the end of
618 *  \a entry which is not counted toward \a length, i.e.
619 *  \code strlen(entry) == length \endcode
620 */
621typedef struct {
622   FLAC__uint32 length;
623   FLAC__byte *entry;
624} FLAC__StreamMetadata_VorbisComment_Entry;
625
626extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
627
628
629/** FLAC VORBIS_COMMENT structure.  (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
630 */
631typedef struct {
632   FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
633   FLAC__uint32 num_comments;
634   FLAC__StreamMetadata_VorbisComment_Entry *comments;
635} FLAC__StreamMetadata_VorbisComment;
636
637extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
638
639
640/** FLAC CUESHEET track index structure.  (See the
641 * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
642 * the full description of each field.)
643 */
644typedef struct {
645   FLAC__uint64 offset;
646   /**< Offset in samples, relative to the track offset, of the index
647    * point.
648    */
649
650   FLAC__byte number;
651   /**< The index point number. */
652} FLAC__StreamMetadata_CueSheet_Index;
653
654extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
655extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
656extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
657
658
659/** FLAC CUESHEET track structure.  (See the
660 * <A HREF="../format.html#cuesheet_track">format specification</A> for
661 * the full description of each field.)
662 */
663typedef struct {
664   FLAC__uint64 offset;
665   /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
666
667   FLAC__byte number;
668   /**< The track number. */
669
670   char isrc[13];
671   /**< Track ISRC.  This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
672
673   unsigned type:1;
674   /**< The track type: 0 for audio, 1 for non-audio. */
675
676   unsigned pre_emphasis:1;
677   /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
678
679   FLAC__byte num_indices;
680   /**< The number of track index points. */
681
682   FLAC__StreamMetadata_CueSheet_Index *indices;
683   /**< NULL if num_indices == 0, else pointer to array of index points. */
684
685} FLAC__StreamMetadata_CueSheet_Track;
686
687extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
688extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
689extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
690extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
691extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
692extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
693extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
694
695
696/** FLAC CUESHEET structure.  (See the
697 * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
698 * for the full description of each field.)
699 */
700typedef struct {
701   char media_catalog_number[129];
702   /**< Media catalog number, in ASCII printable characters 0x20-0x7e.  In
703    * general, the media catalog number may be 0 to 128 bytes long; any
704    * unused characters should be right-padded with NUL characters.
705    */
706
707   FLAC__uint64 lead_in;
708   /**< The number of lead-in samples. */
709
710   FLAC__bool is_cd;
711   /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
712
713   unsigned num_tracks;
714   /**< The number of tracks. */
715
716   FLAC__StreamMetadata_CueSheet_Track *tracks;
717   /**< NULL if num_tracks == 0, else pointer to array of tracks. */
718
719} FLAC__StreamMetadata_CueSheet;
720
721extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
722extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
723extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
724extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
725extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
726
727
728/** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
729typedef enum {
730   FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
731   FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
732   FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
733   FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
734   FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
735   FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
736   FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
737   FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
738   FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
739   FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
740   FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
741   FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
742   FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
743   FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
744   FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
745   FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
746   FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
747   FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
748   FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
749   FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
750   FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
751   FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
752} FLAC__StreamMetadata_Picture_Type;
753
754/** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
755 *
756 *  Using a FLAC__StreamMetadata_Picture_Type as the index to this array
757 *  will give the string equivalent.  The contents should not be
758 *  modified.
759 */
760extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
761
762/** FLAC PICTURE structure.  (See the
763 * <A HREF="../format.html#metadata_block_picture">format specification</A>
764 * for the full description of each field.)
765 */
766typedef struct {
767   FLAC__StreamMetadata_Picture_Type type;
768   /**< The kind of picture stored. */
769
770   char *mime_type;
771   /**< Picture data's MIME type, in ASCII printable characters
772    * 0x20-0x7e, NUL terminated.  For best compatibility with players,
773    * use picture data of MIME type \c image/jpeg or \c image/png.  A
774    * MIME type of '-->' is also allowed, in which case the picture
775    * data should be a complete URL.  In file storage, the MIME type is
776    * stored as a 32-bit length followed by the ASCII string with no NUL
777    * terminator, but is converted to a plain C string in this structure
778    * for convenience.
779    */
780
781   FLAC__byte *description;
782   /**< Picture's description in UTF-8, NUL terminated.  In file storage,
783    * the description is stored as a 32-bit length followed by the UTF-8
784    * string with no NUL terminator, but is converted to a plain C string
785    * in this structure for convenience.
786    */
787
788   FLAC__uint32 width;
789   /**< Picture's width in pixels. */
790
791   FLAC__uint32 height;
792   /**< Picture's height in pixels. */
793
794   FLAC__uint32 depth;
795   /**< Picture's color depth in bits-per-pixel. */
796
797   FLAC__uint32 colors;
798   /**< For indexed palettes (like GIF), picture's number of colors (the
799    * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
800    */
801
802   FLAC__uint32 data_length;
803   /**< Length of binary picture data in bytes. */
804
805   FLAC__byte *data;
806   /**< Binary picture data. */
807
808} FLAC__StreamMetadata_Picture;
809
810extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
811extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
812extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
813extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
814extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
815extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
816extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
817extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
818
819
820/** Structure that is used when a metadata block of unknown type is loaded.
821 *  The contents are opaque.  The structure is used only internally to
822 *  correctly handle unknown metadata.
823 */
824typedef struct {
825   FLAC__byte *data;
826} FLAC__StreamMetadata_Unknown;
827
828
829/** FLAC metadata block structure.  (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
830 */
831typedef struct {
832   FLAC__MetadataType type;
833   /**< The type of the metadata block; used determine which member of the
834    * \a data union to dereference.  If type >= FLAC__METADATA_TYPE_UNDEFINED
835    * then \a data.unknown must be used. */
836
837   FLAC__bool is_last;
838   /**< \c true if this metadata block is the last, else \a false */
839
840   unsigned length;
841   /**< Length, in bytes, of the block data as it appears in the stream. */
842
843   union {
844      FLAC__StreamMetadata_StreamInfo stream_info;
845      FLAC__StreamMetadata_Padding padding;
846      FLAC__StreamMetadata_Application application;
847      FLAC__StreamMetadata_SeekTable seek_table;
848      FLAC__StreamMetadata_VorbisComment vorbis_comment;
849      FLAC__StreamMetadata_CueSheet cue_sheet;
850      FLAC__StreamMetadata_Picture picture;
851      FLAC__StreamMetadata_Unknown unknown;
852   } data;
853   /**< Polymorphic block data; use the \a type value to determine which
854    * to use. */
855} FLAC__StreamMetadata;
856
857extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
858extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
859extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
860
861/** The total stream length of a metadata block header in bytes. */
862#define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
863
864/*****************************************************************************/
865
866
867/*****************************************************************************
868 *
869 * Utility functions
870 *
871 *****************************************************************************/
872
873/** Tests that a sample rate is valid for FLAC.
874 *
875 * \param sample_rate  The sample rate to test for compliance.
876 * \retval FLAC__bool
877 *    \c true if the given sample rate conforms to the specification, else
878 *    \c false.
879 */
880FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
881
882/** Tests that a sample rate is valid for the FLAC subset.  The subset rules
883 *  for valid sample rates are slightly more complex since the rate has to
884 *  be expressible completely in the frame header.
885 *
886 * \param sample_rate  The sample rate to test for compliance.
887 * \retval FLAC__bool
888 *    \c true if the given sample rate conforms to the specification for the
889 *    subset, else \c false.
890 */
891FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
892
893/** Check a Vorbis comment entry name to see if it conforms to the Vorbis
894 *  comment specification.
895 *
896 *  Vorbis comment names must be composed only of characters from
897 *  [0x20-0x3C,0x3E-0x7D].
898 *
899 * \param name       A NUL-terminated string to be checked.
900 * \assert
901 *    \code name != NULL \endcode
902 * \retval FLAC__bool
903 *    \c false if entry name is illegal, else \c true.
904 */
905FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
906
907/** Check a Vorbis comment entry value to see if it conforms to the Vorbis
908 *  comment specification.
909 *
910 *  Vorbis comment values must be valid UTF-8 sequences.
911 *
912 * \param value      A string to be checked.
913 * \param length     A the length of \a value in bytes.  May be
914 *                   \c (unsigned)(-1) to indicate that \a value is a plain
915 *                   UTF-8 NUL-terminated string.
916 * \assert
917 *    \code value != NULL \endcode
918 * \retval FLAC__bool
919 *    \c false if entry name is illegal, else \c true.
920 */
921FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
922
923/** Check a Vorbis comment entry to see if it conforms to the Vorbis
924 *  comment specification.
925 *
926 *  Vorbis comment entries must be of the form 'name=value', and 'name' and
927 *  'value' must be legal according to
928 *  FLAC__format_vorbiscomment_entry_name_is_legal() and
929 *  FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
930 *
931 * \param entry      An entry to be checked.
932 * \param length     The length of \a entry in bytes.
933 * \assert
934 *    \code value != NULL \endcode
935 * \retval FLAC__bool
936 *    \c false if entry name is illegal, else \c true.
937 */
938FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
939
940/** Check a seek table to see if it conforms to the FLAC specification.
941 *  See the format specification for limits on the contents of the
942 *  seek table.
943 *
944 * \param seek_table  A pointer to a seek table to be checked.
945 * \assert
946 *    \code seek_table != NULL \endcode
947 * \retval FLAC__bool
948 *    \c false if seek table is illegal, else \c true.
949 */
950FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
951
952/** Sort a seek table's seek points according to the format specification.
953 *  This includes a "unique-ification" step to remove duplicates, i.e.
954 *  seek points with identical \a sample_number values.  Duplicate seek
955 *  points are converted into placeholder points and sorted to the end of
956 *  the table.
957 *
958 * \param seek_table  A pointer to a seek table to be sorted.
959 * \assert
960 *    \code seek_table != NULL \endcode
961 * \retval unsigned
962 *    The number of duplicate seek points converted into placeholders.
963 */
964FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
965
966/** Check a cue sheet to see if it conforms to the FLAC specification.
967 *  See the format specification for limits on the contents of the
968 *  cue sheet.
969 *
970 * \param cue_sheet  A pointer to an existing cue sheet to be checked.
971 * \param check_cd_da_subset  If \c true, check CUESHEET against more
972 *                   stringent requirements for a CD-DA (audio) disc.
973 * \param violation  Address of a pointer to a string.  If there is a
974 *                   violation, a pointer to a string explanation of the
975 *                   violation will be returned here. \a violation may be
976 *                   \c NULL if you don't need the returned string.  Do not
977 *                   free the returned string; it will always point to static
978 *                   data.
979 * \assert
980 *    \code cue_sheet != NULL \endcode
981 * \retval FLAC__bool
982 *    \c false if cue sheet is illegal, else \c true.
983 */
984FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
985
986/** Check picture data to see if it conforms to the FLAC specification.
987 *  See the format specification for limits on the contents of the
988 *  PICTURE block.
989 *
990 * \param picture    A pointer to existing picture data to be checked.
991 * \param violation  Address of a pointer to a string.  If there is a
992 *                   violation, a pointer to a string explanation of the
993 *                   violation will be returned here. \a violation may be
994 *                   \c NULL if you don't need the returned string.  Do not
995 *                   free the returned string; it will always point to static
996 *                   data.
997 * \assert
998 *    \code picture != NULL \endcode
999 * \retval FLAC__bool
1000 *    \c false if picture data is illegal, else \c true.
1001 */
1002FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
1003
1004/* \} */
1005
1006#ifdef __cplusplus
1007}
1008#endif
1009
1010#endif
src/lib/libflac/include/protected/stream_encoder.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PROTECTED__STREAM_ENCODER_H
33#define FLAC__PROTECTED__STREAM_ENCODER_H
34
35#include "flac/stream_encoder.h"
36#if FLAC__HAS_OGG
37#include "private/ogg_encoder_aspect.h"
38#endif
39
40#ifndef FLAC__INTEGER_ONLY_LIBRARY
41
42#include "private/float.h"
43
44#define FLAC__MAX_APODIZATION_FUNCTIONS 32
45
46typedef enum {
47   FLAC__APODIZATION_BARTLETT,
48   FLAC__APODIZATION_BARTLETT_HANN,
49   FLAC__APODIZATION_BLACKMAN,
50   FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
51   FLAC__APODIZATION_CONNES,
52   FLAC__APODIZATION_FLATTOP,
53   FLAC__APODIZATION_GAUSS,
54   FLAC__APODIZATION_HAMMING,
55   FLAC__APODIZATION_HANN,
56   FLAC__APODIZATION_KAISER_BESSEL,
57   FLAC__APODIZATION_NUTTALL,
58   FLAC__APODIZATION_RECTANGLE,
59   FLAC__APODIZATION_TRIANGLE,
60   FLAC__APODIZATION_TUKEY,
61   FLAC__APODIZATION_WELCH
62} FLAC__ApodizationFunction;
63
64typedef struct {
65   FLAC__ApodizationFunction type;
66   union {
67      struct {
68         FLAC__real stddev;
69      } gauss;
70      struct {
71         FLAC__real p;
72      } tukey;
73   } parameters;
74} FLAC__ApodizationSpecification;
75
76#endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
77
78typedef struct FLAC__StreamEncoderProtected {
79   FLAC__StreamEncoderState state;
80   FLAC__bool verify;
81   FLAC__bool streamable_subset;
82   FLAC__bool do_md5;
83   FLAC__bool do_mid_side_stereo;
84   FLAC__bool loose_mid_side_stereo;
85   unsigned channels;
86   unsigned bits_per_sample;
87   unsigned sample_rate;
88   unsigned blocksize;
89#ifndef FLAC__INTEGER_ONLY_LIBRARY
90   unsigned num_apodizations;
91   FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
92#endif
93   unsigned max_lpc_order;
94   unsigned qlp_coeff_precision;
95   FLAC__bool do_qlp_coeff_prec_search;
96   FLAC__bool do_exhaustive_model_search;
97   FLAC__bool do_escape_coding;
98   unsigned min_residual_partition_order;
99   unsigned max_residual_partition_order;
100   unsigned rice_parameter_search_dist;
101   FLAC__uint64 total_samples_estimate;
102   FLAC__StreamMetadata **metadata;
103   unsigned num_metadata_blocks;
104   FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
105#if FLAC__HAS_OGG
106   FLAC__OggEncoderAspect ogg_encoder_aspect;
107#endif
108} FLAC__StreamEncoderProtected;
109
110#endif
src/lib/libflac/include/protected/stream_decoder.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PROTECTED__STREAM_DECODER_H
33#define FLAC__PROTECTED__STREAM_DECODER_H
34
35#include "flac/stream_decoder.h"
36#if FLAC__HAS_OGG
37#include "private/ogg_decoder_aspect.h"
38#endif
39
40typedef struct FLAC__StreamDecoderProtected {
41   FLAC__StreamDecoderState state;
42   unsigned channels;
43   FLAC__ChannelAssignment channel_assignment;
44   unsigned bits_per_sample;
45   unsigned sample_rate; /* in Hz */
46   unsigned blocksize; /* in samples (per channel) */
47   FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
48#if FLAC__HAS_OGG
49   FLAC__OggDecoderAspect ogg_decoder_aspect;
50#endif
51} FLAC__StreamDecoderProtected;
52
53/*
54 * return the number of input bytes consumed
55 */
56unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
57
58#endif
src/lib/libflac/include/protected/all.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PROTECTED__ALL_H
33#define FLAC__PROTECTED__ALL_H
34
35#include "stream_decoder.h"
36#include "stream_encoder.h"
37
38#endif
src/lib/libflac/include/private/bitwriter.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__BITWRITER_H
33#define FLAC__PRIVATE__BITWRITER_H
34
35#include <stdio.h> /* for FILE */
36#include "flac/ordinals.h"
37
38/*
39 * opaque structure definition
40 */
41struct FLAC__BitWriter;
42typedef struct FLAC__BitWriter FLAC__BitWriter;
43
44/*
45 * construction, deletion, initialization, etc functions
46 */
47FLAC__BitWriter *FLAC__bitwriter_new(void);
48void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
49FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
50void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
51void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
52void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
53
54/*
55 * CRC functions
56 *
57 * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
58 */
59FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
60FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
61
62/*
63 * info functions
64 */
65FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
66unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
67
68/*
69 * direct buffer access
70 *
71 * there may be no calls on the bitwriter between get and release.
72 * the bitwriter continues to own the returned buffer.
73 * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
74 */
75FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
76void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
77
78/*
79 * write functions
80 */
81FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
82FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
83FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
84FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
85FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
86FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
87FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
88unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
89#if 0 /* UNUSED */
90unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
91unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
92#endif
93FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
94FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
95#if 0 /* UNUSED */
96FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
97FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
98#endif
99FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
100FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
101FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
102
103#endif
src/lib/libflac/include/private/stream_encoder_framing.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
33#define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
34
35#include "flac/format.h"
36#include "bitwriter.h"
37
38FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
39FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
40FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
41FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
42FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
43FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
44
45#endif
src/lib/libflac/include/private/lpc.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__LPC_H
33#define FLAC__PRIVATE__LPC_H
34
35#ifdef HAVE_CONFIG_H
36#include <config.h>
37#endif
38
39#include "private/float.h"
40#include "flac/format.h"
41
42#ifndef FLAC__INTEGER_ONLY_LIBRARY
43
44/*
45 *   FLAC__lpc_window_data()
46 *   --------------------------------------------------------------------
47 *   Applies the given window to the data.
48 *  OPT: asm implementation
49 *
50 *   IN in[0,data_len-1]
51 *   IN window[0,data_len-1]
52 *   OUT out[0,lag-1]
53 *   IN data_len
54 */
55void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
56
57/*
58 *   FLAC__lpc_compute_autocorrelation()
59 *   --------------------------------------------------------------------
60 *   Compute the autocorrelation for lags between 0 and lag-1.
61 *   Assumes data[] outside of [0,data_len-1] == 0.
62 *   Asserts that lag > 0.
63 *
64 *   IN data[0,data_len-1]
65 *   IN data_len
66 *   IN 0 < lag <= data_len
67 *   OUT autoc[0,lag-1]
68 */
69void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
70#ifndef FLAC__NO_ASM
71#  ifdef FLAC__CPU_IA32
72#    ifdef FLAC__HAS_NASM
73void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
74void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
75void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
76void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
77void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
78#    endif
79#  endif
80#endif
81
82/*
83 *   FLAC__lpc_compute_lp_coefficients()
84 *   --------------------------------------------------------------------
85 *   Computes LP coefficients for orders 1..max_order.
86 *   Do not call if autoc[0] == 0.0.  This means the signal is zero
87 *   and there is no point in calculating a predictor.
88 *
89 *   IN autoc[0,max_order]                      autocorrelation values
90 *   IN 0 < max_order <= FLAC__MAX_LPC_ORDER    max LP order to compute
91 *   OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
92 *   *** IMPORTANT:
93 *   *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
94 *   OUT error[0,max_order-1]                   error for each order (more
95 *                                              specifically, the variance of
96 *                                              the error signal times # of
97 *                                              samples in the signal)
98 *
99 *   Example: if max_order is 9, the LP coefficients for order 9 will be
100 *            in lp_coeff[8][0,8], the LP coefficients for order 8 will be
101 *          in lp_coeff[7][0,7], etc.
102 */
103void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
104
105/*
106 *   FLAC__lpc_quantize_coefficients()
107 *   --------------------------------------------------------------------
108 *   Quantizes the LP coefficients.  NOTE: precision + bits_per_sample
109 *   must be less than 32 (sizeof(FLAC__int32)*8).
110 *
111 *   IN lp_coeff[0,order-1]    LP coefficients
112 *   IN order                  LP order
113 *   IN FLAC__MIN_QLP_COEFF_PRECISION < precision
114 *                             desired precision (in bits, including sign
115 *                             bit) of largest coefficient
116 *   OUT qlp_coeff[0,order-1]  quantized coefficients
117 *   OUT shift                 # of bits to shift right to get approximated
118 *                             LP coefficients.  NOTE: could be negative.
119 *   RETURN 0 => quantization OK
120 *          1 => coefficients require too much shifting for *shift to
121 *              fit in the LPC subframe header.  'shift' is unset.
122 *         2 => coefficients are all zero, which is bad.  'shift' is
123 *              unset.
124 */
125int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
126
127/*
128 *   FLAC__lpc_compute_residual_from_qlp_coefficients()
129 *   --------------------------------------------------------------------
130 *   Compute the residual signal obtained from sutracting the predicted
131 *   signal from the original.
132 *
133 *   IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
134 *   IN data_len                length of original signal
135 *   IN qlp_coeff[0,order-1]    quantized LP coefficients
136 *   IN order > 0               LP order
137 *   IN lp_quantization         quantization of LP coefficients in bits
138 *   OUT residual[0,data_len-1] residual signal
139 */
140void 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[]);
141void 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[]);
142#ifndef FLAC__NO_ASM
143#  ifdef FLAC__CPU_IA32
144#    ifdef FLAC__HAS_NASM
145void 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[]);
146void 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[]);
147#    endif
148#  endif
149#endif
150
151#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
152
153/*
154 *   FLAC__lpc_restore_signal()
155 *   --------------------------------------------------------------------
156 *   Restore the original signal by summing the residual and the
157 *   predictor.
158 *
159 *   IN residual[0,data_len-1]  residual signal
160 *   IN data_len                length of original signal
161 *   IN qlp_coeff[0,order-1]    quantized LP coefficients
162 *   IN order > 0               LP order
163 *   IN lp_quantization         quantization of LP coefficients in bits
164 *   *** IMPORTANT: the caller must pass in the historical samples:
165 *   IN  data[-order,-1]        previously-reconstructed historical samples
166 *   OUT data[0,data_len-1]     original signal
167 */
168void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[]);
169void 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[]);
170#ifndef FLAC__NO_ASM
171#  ifdef FLAC__CPU_IA32
172#    ifdef FLAC__HAS_NASM
173void 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[]);
174void 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[]);
175#    endif /* FLAC__HAS_NASM */
176#  elif defined FLAC__CPU_PPC
177void 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[]);
178void 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[]);
179#  endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
180#endif /* FLAC__NO_ASM */
181
182#ifndef FLAC__INTEGER_ONLY_LIBRARY
183
184/*
185 *   FLAC__lpc_compute_expected_bits_per_residual_sample()
186 *   --------------------------------------------------------------------
187 *   Compute the expected number of bits per residual signal sample
188 *   based on the LP error (which is related to the residual variance).
189 *
190 *   IN lpc_error >= 0.0   error returned from calculating LP coefficients
191 *   IN total_samples > 0  # of samples in residual signal
192 *   RETURN                expected bits per sample
193 */
194FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
195FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
196
197/*
198 *   FLAC__lpc_compute_best_order()
199 *   --------------------------------------------------------------------
200 *   Compute the best order from the array of signal errors returned
201 *   during coefficient computation.
202 *
203 *   IN lpc_error[0,max_order-1] >= 0.0  error returned from calculating LP coefficients
204 *   IN max_order > 0                    max LP order
205 *   IN total_samples > 0                # of samples in residual signal
206 *   IN overhead_bits_per_order          # of bits overhead for each increased LP order
207 *                                       (includes warmup sample size and quantized LP coefficient)
208 *   RETURN [1,max_order]                best order
209 */
210unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
211
212#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
213
214#endif
src/lib/libflac/include/private/fixed.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__FIXED_H
33#define FLAC__PRIVATE__FIXED_H
34
35#ifdef HAVE_CONFIG_H
36#include <config.h>
37#endif
38
39#include "private/float.h"
40#include "flac/format.h"
41
42/*
43 *   FLAC__fixed_compute_best_predictor()
44 *   --------------------------------------------------------------------
45 *   Compute the best fixed predictor and the expected bits-per-sample
46 *  of the residual signal for each order.  The _wide() version uses
47 *  64-bit integers which is statistically necessary when bits-per-
48 *  sample + log2(blocksize) > 30
49 *
50 *   IN data[0,data_len-1]
51 *   IN data_len
52 *   OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
53 */
54#ifndef FLAC__INTEGER_ONLY_LIBRARY
55unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
56# ifndef FLAC__NO_ASM
57#  ifdef FLAC__CPU_IA32
58#   ifdef FLAC__HAS_NASM
59unsigned 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]);
60#   endif
61#  endif
62# endif
63unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
64#else
65unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
66unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
67#endif
68
69/*
70 *   FLAC__fixed_compute_residual()
71 *   --------------------------------------------------------------------
72 *   Compute the residual signal obtained from sutracting the predicted
73 *   signal from the original.
74 *
75 *   IN data[-order,data_len-1]        original signal (NOTE THE INDICES!)
76 *   IN data_len                       length of original signal
77 *   IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
78 *   OUT residual[0,data_len-1]        residual signal
79 */
80void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
81
82/*
83 *   FLAC__fixed_restore_signal()
84 *   --------------------------------------------------------------------
85 *   Restore the original signal by summing the residual and the
86 *   predictor.
87 *
88 *   IN residual[0,data_len-1]         residual signal
89 *   IN data_len                       length of original signal
90 *   IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
91 *   *** IMPORTANT: the caller must pass in the historical samples:
92 *   IN  data[-order,-1]               previously-reconstructed historical samples
93 *   OUT data[0,data_len-1]            original signal
94 */
95void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
96
97#endif
src/lib/libflac/include/private/metadata.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__METADATA_H
33#define FLAC__PRIVATE__METADATA_H
34
35#include "flac/metadata.h"
36
37/* WATCHOUT: all malloc()ed data in the block is free()ed; this may not
38 * be a consistent state (e.g. PICTURE) or equivalent to the initial
39 * state after FLAC__metadata_object_new()
40 */
41void FLAC__metadata_object_delete_data(FLAC__StreamMetadata *object);
42
43void FLAC__metadata_object_cuesheet_track_delete_data(FLAC__StreamMetadata_CueSheet_Track *object);
44
45#endif
src/lib/libflac/include/private/bitreader.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__BITREADER_H
33#define FLAC__PRIVATE__BITREADER_H
34
35#include <stdio.h> /* for FILE */
36#include "flac/ordinals.h"
37#include "cpu.h"
38
39/*
40 * opaque structure definition
41 */
42struct FLAC__BitReader;
43typedef struct FLAC__BitReader FLAC__BitReader;
44
45typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
46
47/*
48 * construction, deletion, initialization, etc functions
49 */
50FLAC__BitReader *FLAC__bitreader_new(void);
51void FLAC__bitreader_delete(FLAC__BitReader *br);
52FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
53void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
54FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
55void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
56
57/*
58 * CRC functions
59 */
60void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
61FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
62
63/*
64 * info functions
65 */
66FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
67unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
68unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
69
70/*
71 * read functions
72 */
73
74FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
75FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
76FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
77FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
78FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
79FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
80FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
81FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
82FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
83FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
84#ifndef FLAC__NO_ASM
85#  ifdef FLAC__CPU_IA32
86#    ifdef FLAC__HAS_NASM
87FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
88#    endif
89#  endif
90#endif
91#if 0 /* UNUSED */
92FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
93FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
94#endif
95FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
96FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
97
98FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
99#endif
src/lib/libflac/include/private/float.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__FLOAT_H
33#define FLAC__PRIVATE__FLOAT_H
34
35#ifdef HAVE_CONFIG_H
36#include <config.h>
37#endif
38
39#include "flac/ordinals.h"
40
41/*
42 * These typedefs make it easier to ensure that integer versions of
43 * the library really only contain integer operations.  All the code
44 * in libFLAC should use FLAC__float and FLAC__double in place of
45 * float and double, and be protected by checks of the macro
46 * FLAC__INTEGER_ONLY_LIBRARY.
47 *
48 * FLAC__real is the basic floating point type used in LPC analysis.
49 */
50#ifndef FLAC__INTEGER_ONLY_LIBRARY
51typedef double FLAC__double;
52typedef float FLAC__float;
53/*
54 * WATCHOUT: changing FLAC__real will change the signatures of many
55 * functions that have assembly language equivalents and break them.
56 */
57typedef float FLAC__real;
58#else
59/*
60 * The convention for FLAC__fixedpoint is to use the upper 16 bits
61 * for the integer part and lower 16 bits for the fractional part.
62 */
63typedef FLAC__int32 FLAC__fixedpoint;
64extern const FLAC__fixedpoint FLAC__FP_ZERO;
65extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
66extern const FLAC__fixedpoint FLAC__FP_ONE;
67extern const FLAC__fixedpoint FLAC__FP_LN2;
68extern const FLAC__fixedpoint FLAC__FP_E;
69
70#define FLAC__fixedpoint_trunc(x) ((x)>>16)
71
72#define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
73
74#define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
75
76/*
77 *   FLAC__fixedpoint_log2()
78 *   --------------------------------------------------------------------
79 *   Returns the base-2 logarithm of the fixed-point number 'x' using an
80 *   algorithm by Knuth for x >= 1.0
81 *
82 *   'fracbits' is the number of fractional bits of 'x'.  'fracbits' must
83 *   be < 32 and evenly divisible by 4 (0 is OK but not very precise).
84 *
85 *   'precision' roughly limits the number of iterations that are done;
86 *   use (unsigned)(-1) for maximum precision.
87 *
88 *   If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
89 *   function will punt and return 0.
90 *
91 *   The return value will also have 'fracbits' fractional bits.
92 */
93FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
94
95#endif
96
97#endif
src/lib/libflac/include/private/md5.h
r0r14135
1#ifndef FLAC__PRIVATE__MD5_H
2#define FLAC__PRIVATE__MD5_H
3
4/*
5 * This is the header file for the MD5 message-digest algorithm.
6 * The algorithm is due to Ron Rivest.  This code was
7 * written by Colin Plumb in 1993, no copyright is claimed.
8 * This code is in the public domain; do with it what you wish.
9 *
10 * Equivalent code is available from RSA Data Security, Inc.
11 * This code has been tested against that, and is equivalent,
12 * except that you don't need to include two pages of legalese
13 * with every copy.
14 *
15 * To compute the message digest of a chunk of bytes, declare an
16 * MD5Context structure, pass it to MD5Init, call MD5Update as
17 * needed on buffers full of bytes, and then call MD5Final, which
18 * will fill a supplied 16-byte array with the digest.
19 *
20 * Changed so as no longer to depend on Colin Plumb's `usual.h'
21 * header definitions; now uses stuff from dpkg's config.h
22 *  - Ian Jackson <ijackson@nyx.cs.du.edu>.
23 * Still in the public domain.
24 *
25 * Josh Coalson: made some changes to integrate with libFLAC.
26 * Still in the public domain, with no warranty.
27 */
28
29#include "flac/ordinals.h"
30
31typedef struct {
32   FLAC__uint32 in[16];
33   FLAC__uint32 buf[4];
34   FLAC__uint32 bytes[2];
35   FLAC__byte *internal_buf;
36   size_t capacity;
37} FLAC__MD5Context;
38
39void FLAC__MD5Init(FLAC__MD5Context *context);
40void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
41
42FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
43
44#endif
src/lib/libflac/include/private/cpu.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__CPU_H
33#define FLAC__PRIVATE__CPU_H
34
35#include "flac/ordinals.h"
36
37#ifdef HAVE_CONFIG_H
38#include <config.h>
39#endif
40
41typedef enum {
42   FLAC__CPUINFO_TYPE_IA32,
43   FLAC__CPUINFO_TYPE_PPC,
44   FLAC__CPUINFO_TYPE_UNKNOWN
45} FLAC__CPUInfo_Type;
46
47typedef struct {
48   FLAC__bool cpuid;
49   FLAC__bool bswap;
50   FLAC__bool cmov;
51   FLAC__bool mmx;
52   FLAC__bool fxsr;
53   FLAC__bool sse;
54   FLAC__bool sse2;
55   FLAC__bool sse3;
56   FLAC__bool ssse3;
57   FLAC__bool _3dnow;
58   FLAC__bool ext3dnow;
59   FLAC__bool extmmx;
60} FLAC__CPUInfo_IA32;
61
62typedef struct {
63   FLAC__bool altivec;
64   FLAC__bool ppc64;
65} FLAC__CPUInfo_PPC;
66
67typedef struct {
68   FLAC__bool use_asm;
69   FLAC__CPUInfo_Type type;
70   union {
71      FLAC__CPUInfo_IA32 ia32;
72      FLAC__CPUInfo_PPC ppc;
73   } data;
74} FLAC__CPUInfo;
75
76void FLAC__cpu_info(FLAC__CPUInfo *info);
77
78#ifndef FLAC__NO_ASM
79#ifdef FLAC__CPU_IA32
80#ifdef FLAC__HAS_NASM
81FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
82void         FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
83FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
84#endif
85#endif
86#endif
87
88#endif
src/lib/libflac/include/private/crc.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__CRC_H
33#define FLAC__PRIVATE__CRC_H
34
35#include "flac/ordinals.h"
36
37/* 8 bit CRC generator, MSB shifted first
38** polynomial = x^8 + x^2 + x^1 + x^0
39** init = 0
40*/
41extern FLAC__byte const FLAC__crc8_table[256];
42#define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
43void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
44void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
45FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
46
47/* 16 bit CRC generator, MSB shifted first
48** polynomial = x^16 + x^15 + x^2 + x^0
49** init = 0
50*/
51extern unsigned FLAC__crc16_table[256];
52
53#define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
54/* this alternate may be faster on some systems/compilers */
55#if 0
56#define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
57#endif
58
59unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
60
61#endif
src/lib/libflac/include/private/window.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__WINDOW_H
33#define FLAC__PRIVATE__WINDOW_H
34
35#ifdef HAVE_CONFIG_H
36#include <config.h>
37#endif
38
39#include "private/float.h"
40#include "flac/format.h"
41
42#ifndef FLAC__INTEGER_ONLY_LIBRARY
43
44/*
45 *   FLAC__window_*()
46 *   --------------------------------------------------------------------
47 *   Calculates window coefficients according to different apodization
48 *   functions.
49 *
50 *   OUT window[0,L-1]
51 *   IN L (number of points in window)
52 */
53void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
54void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
55void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
56void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
57void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
58void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
59void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
60void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
61void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
62void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
63void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
64void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
65void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
66void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
67void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
68
69#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
70
71#endif
src/lib/libflac/include/private/all.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__ALL_H
33#define FLAC__PRIVATE__ALL_H
34
35#include "bitmath.h"
36#include "bitreader.h"
37#include "bitwriter.h"
38#include "cpu.h"
39#include "crc.h"
40#include "fixed.h"
41#include "float.h"
42#include "format.h"
43#include "lpc.h"
44#include "md5.h"
45#include "memory.h"
46#include "metadata.h"
47#include "stream_encoder_framing.h"
48
49#endif
src/lib/libflac/include/private/bitmath.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__BITMATH_H
33#define FLAC__PRIVATE__BITMATH_H
34
35#include "flac/ordinals.h"
36
37unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
38unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
39unsigned FLAC__bitmath_silog2(int v);
40unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
41
42#endif
src/lib/libflac/include/private/format.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__FORMAT_H
33#define FLAC__PRIVATE__FORMAT_H
34
35#include "flac/format.h"
36
37unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
38unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
39unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
40void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
41void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
42FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
43
44#endif
src/lib/libflac/include/private/memory.h
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLAC__PRIVATE__MEMORY_H
33#define FLAC__PRIVATE__MEMORY_H
34
35#ifdef HAVE_CONFIG_H
36#include <config.h>
37#endif
38
39#include <stdlib.h> /* for size_t */
40
41#include "private/float.h"
42#include "flac/ordinals.h" /* for FLAC__bool */
43
44/* Returns the unaligned address returned by malloc.
45 * Use free() on this address to deallocate.
46 */
47void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
48FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
49FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
50FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
51FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
52#ifndef FLAC__INTEGER_ONLY_LIBRARY
53FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
54#endif
55
56#endif
src/lib/libflac/include/flac++/encoder.h
r0r14135
1/* libFLAC++ - Free Lossless Audio Codec library
2 * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLACPP__ENCODER_H
33#define FLACPP__ENCODER_H
34
35#include "export.h"
36
37#include "flac/stream_encoder.h"
38#include "decoder.h"
39#include "metadata.h"
40
41
42/** \file include/FLAC++/encoder.h
43 *
44 *  \brief
45 *  This module contains the classes which implement the various
46 *  encoders.
47 *
48 *  See the detailed documentation in the
49 *  \link flacpp_encoder encoder \endlink module.
50 */
51
52/** \defgroup flacpp_encoder FLAC++/encoder.h: encoder classes
53 *  \ingroup flacpp
54 *
55 *  \brief
56 *  This module describes the encoder layers provided by libFLAC++.
57 *
58 * The libFLAC++ encoder classes are object wrappers around their
59 * counterparts in libFLAC.  All encoding layers available in
60 * libFLAC are also provided here.  The interface is very similar;
61 * make sure to read the \link flac_encoder libFLAC encoder module \endlink.
62 *
63 * There are only two significant differences here.  First, instead of
64 * passing in C function pointers for callbacks, you inherit from the
65 * encoder class and provide implementations for the callbacks in your
66 * derived class; because of this there is no need for a 'client_data'
67 * property.
68 *
69 * Second, there are two stream encoder classes.  FLAC::Encoder::Stream
70 * is used for the same cases that FLAC__stream_encoder_init_stream() /
71 * FLAC__stream_encoder_init_ogg_stream() are used, and FLAC::Encoder::File
72 * is used for the same cases that
73 * FLAC__stream_encoder_init_FILE() and FLAC__stream_encoder_init_file() /
74 * FLAC__stream_encoder_init_ogg_FILE() and FLAC__stream_encoder_init_ogg_file()
75 * are used.
76 */
77
78namespace FLAC {
79   namespace Encoder {
80
81      /** \ingroup flacpp_encoder
82       *  \brief
83       *  This class wraps the ::FLAC__StreamEncoder.  If you are
84       *  encoding to a file, FLAC::Encoder::File may be more
85       *  convenient.
86       *
87       * The usage of this class is similar to FLAC__StreamEncoder,
88       * except instead of providing callbacks to
89       * FLAC__stream_encoder_init*_stream(), you will inherit from this
90       * class and override the virtual callback functions with your
91       * own implementations, then call init() or init_ogg().  The rest of
92       * the calls work the same as in the C layer.
93       *
94       * Only the write callback is mandatory.  The others are
95       * optional; this class provides default implementations that do
96       * nothing.  In order for some STREAMINFO and SEEKTABLE data to
97       * be written properly, you must overide seek_callback() and
98       * tell_callback(); see FLAC__stream_encoder_init_stream() as to
99       * why.
100       */
101      class FLACPP_API Stream {
102      public:
103         /** This class is a wrapper around FLAC__StreamEncoderState.
104          */
105         class FLACPP_API State {
106         public:
107            inline State(::FLAC__StreamEncoderState state): state_(state) { }
108            inline operator ::FLAC__StreamEncoderState() const { return state_; }
109            inline const char *as_cstring() const { return ::FLAC__StreamEncoderStateString[state_]; }
110            inline const char *resolved_as_cstring(const Stream &encoder) const { return ::FLAC__stream_encoder_get_resolved_state_string(encoder.encoder_); }
111         protected:
112            ::FLAC__StreamEncoderState state_;
113         };
114
115         Stream();
116         virtual ~Stream();
117
118         //@{
119         /** Call after construction to check the that the object was created
120          *  successfully.  If not, use get_state() to find out why not.
121          *
122          */
123         virtual bool is_valid() const;
124         inline operator bool() const { return is_valid(); } ///< See is_valid()
125         //@}
126
127         virtual bool set_ogg_serial_number(long value);                 ///< See FLAC__stream_encoder_set_ogg_serial_number()
128         virtual bool set_verify(bool value);                            ///< See FLAC__stream_encoder_set_verify()
129         virtual bool set_streamable_subset(bool value);                 ///< See FLAC__stream_encoder_set_streamable_subset()
130         virtual bool set_channels(unsigned value);                      ///< See FLAC__stream_encoder_set_channels()
131         virtual bool set_bits_per_sample(unsigned value);               ///< See FLAC__stream_encoder_set_bits_per_sample()
132         virtual bool set_sample_rate(unsigned value);                   ///< See FLAC__stream_encoder_set_sample_rate()
133         virtual bool set_compression_level(unsigned value);             ///< See FLAC__stream_encoder_set_compression_level()
134         virtual bool set_blocksize(unsigned value);                     ///< See FLAC__stream_encoder_set_blocksize()
135         virtual bool set_do_mid_side_stereo(bool value);                ///< See FLAC__stream_encoder_set_do_mid_side_stereo()
136         virtual bool set_loose_mid_side_stereo(bool value);             ///< See FLAC__stream_encoder_set_loose_mid_side_stereo()
137         virtual bool set_apodization(const char *specification);        ///< See FLAC__stream_encoder_set_apodization()
138         virtual bool set_max_lpc_order(unsigned value);                 ///< See FLAC__stream_encoder_set_max_lpc_order()
139         virtual bool set_qlp_coeff_precision(unsigned value);           ///< See FLAC__stream_encoder_set_qlp_coeff_precision()
140         virtual bool set_do_qlp_coeff_prec_search(bool value);          ///< See FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
141         virtual bool set_do_escape_coding(bool value);                  ///< See FLAC__stream_encoder_set_do_escape_coding()
142         virtual bool set_do_exhaustive_model_search(bool value);        ///< See FLAC__stream_encoder_set_do_exhaustive_model_search()
143         virtual bool set_min_residual_partition_order(unsigned value);  ///< See FLAC__stream_encoder_set_min_residual_partition_order()
144         virtual bool set_max_residual_partition_order(unsigned value);  ///< See FLAC__stream_encoder_set_max_residual_partition_order()
145         virtual bool set_rice_parameter_search_dist(unsigned value);    ///< See FLAC__stream_encoder_set_rice_parameter_search_dist()
146         virtual bool set_total_samples_estimate(FLAC__uint64 value);    ///< See FLAC__stream_encoder_set_total_samples_estimate()
147         virtual bool set_metadata(::FLAC__StreamMetadata **metadata, unsigned num_blocks);    ///< See FLAC__stream_encoder_set_metadata()
148         virtual bool set_metadata(FLAC::Metadata::Prototype **metadata, unsigned num_blocks); ///< See FLAC__stream_encoder_set_metadata()
149
150         /* get_state() is not virtual since we want subclasses to be able to return their own state */
151         State get_state() const;                                   ///< See FLAC__stream_encoder_get_state()
152         virtual Decoder::Stream::State get_verify_decoder_state() const; ///< See FLAC__stream_encoder_get_verify_decoder_state()
153         virtual void get_verify_decoder_error_stats(FLAC__uint64 *absolute_sample, unsigned *frame_number, unsigned *channel, unsigned *sample, FLAC__int32 *expected, FLAC__int32 *got); ///< See FLAC__stream_encoder_get_verify_decoder_error_stats()
154         virtual bool     get_verify() const;                       ///< See FLAC__stream_encoder_get_verify()
155         virtual bool     get_streamable_subset() const;            ///< See FLAC__stream_encoder_get_streamable_subset()
156         virtual bool     get_do_mid_side_stereo() const;           ///< See FLAC__stream_encoder_get_do_mid_side_stereo()
157         virtual bool     get_loose_mid_side_stereo() const;        ///< See FLAC__stream_encoder_get_loose_mid_side_stereo()
158         virtual unsigned get_channels() const;                     ///< See FLAC__stream_encoder_get_channels()
159         virtual unsigned get_bits_per_sample() const;              ///< See FLAC__stream_encoder_get_bits_per_sample()
160         virtual unsigned get_sample_rate() const;                  ///< See FLAC__stream_encoder_get_sample_rate()
161         virtual unsigned get_blocksize() const;                    ///< See FLAC__stream_encoder_get_blocksize()
162         virtual unsigned get_max_lpc_order() const;                ///< See FLAC__stream_encoder_get_max_lpc_order()
163         virtual unsigned get_qlp_coeff_precision() const;          ///< See FLAC__stream_encoder_get_qlp_coeff_precision()
164         virtual bool     get_do_qlp_coeff_prec_search() const;     ///< See FLAC__stream_encoder_get_do_qlp_coeff_prec_search()
165         virtual bool     get_do_escape_coding() const;             ///< See FLAC__stream_encoder_get_do_escape_coding()
166         virtual bool     get_do_exhaustive_model_search() const;   ///< See FLAC__stream_encoder_get_do_exhaustive_model_search()
167         virtual unsigned get_min_residual_partition_order() const; ///< See FLAC__stream_encoder_get_min_residual_partition_order()
168         virtual unsigned get_max_residual_partition_order() const; ///< See FLAC__stream_encoder_get_max_residual_partition_order()
169         virtual unsigned get_rice_parameter_search_dist() const;   ///< See FLAC__stream_encoder_get_rice_parameter_search_dist()
170         virtual FLAC__uint64 get_total_samples_estimate() const;   ///< See FLAC__stream_encoder_get_total_samples_estimate()
171
172         virtual ::FLAC__StreamEncoderInitStatus init();            ///< See FLAC__stream_encoder_init_stream()
173         virtual ::FLAC__StreamEncoderInitStatus init_ogg();        ///< See FLAC__stream_encoder_init_ogg_stream()
174
175         virtual bool finish(); ///< See FLAC__stream_encoder_finish()
176
177         virtual bool process(const FLAC__int32 * const buffer[], unsigned samples);     ///< See FLAC__stream_encoder_process()
178         virtual bool process_interleaved(const FLAC__int32 buffer[], unsigned samples); ///< See FLAC__stream_encoder_process_interleaved()
179      protected:
180         /// See FLAC__StreamEncoderReadCallback
181         virtual ::FLAC__StreamEncoderReadStatus read_callback(FLAC__byte buffer[], size_t *bytes);
182
183         /// See FLAC__StreamEncoderWriteCallback
184         virtual ::FLAC__StreamEncoderWriteStatus write_callback(const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame) = 0;
185
186         /// See FLAC__StreamEncoderSeekCallback
187         virtual ::FLAC__StreamEncoderSeekStatus seek_callback(FLAC__uint64 absolute_byte_offset);
188
189         /// See FLAC__StreamEncoderTellCallback
190         virtual ::FLAC__StreamEncoderTellStatus tell_callback(FLAC__uint64 *absolute_byte_offset);
191
192         /// See FLAC__StreamEncoderMetadataCallback
193         virtual void metadata_callback(const ::FLAC__StreamMetadata *metadata);
194
195#if (defined _MSC_VER) || (defined __BORLANDC__) || (defined __GNUG__ && (__GNUG__ < 2 || (__GNUG__ == 2 && __GNUC_MINOR__ < 96))) || (defined __SUNPRO_CC)
196         // lame hack: some MSVC/GCC versions can't see a protected encoder_ from nested State::resolved_as_cstring()
197         friend State;
198#endif
199         ::FLAC__StreamEncoder *encoder_;
200
201         static ::FLAC__StreamEncoderReadStatus read_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
202         static ::FLAC__StreamEncoderWriteStatus write_callback_(const ::FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
203         static ::FLAC__StreamEncoderSeekStatus seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
204         static ::FLAC__StreamEncoderTellStatus tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
205         static void metadata_callback_(const ::FLAC__StreamEncoder *encoder, const ::FLAC__StreamMetadata *metadata, void *client_data);
206      private:
207         // Private and undefined so you can't use them:
208         Stream(const Stream &);
209         void operator=(const Stream &);
210      };
211
212      /** \ingroup flacpp_encoder
213       *  \brief
214       *  This class wraps the ::FLAC__StreamEncoder.  If you are
215       *  not encoding to a file, you may need to use
216       *  FLAC::Encoder::Stream.
217       *
218       * The usage of this class is similar to FLAC__StreamEncoder,
219       * except instead of providing callbacks to
220       * FLAC__stream_encoder_init*_FILE() or
221       * FLAC__stream_encoder_init*_file(), you will inherit from this
222       * class and override the virtual callback functions with your
223       * own implementations, then call init() or init_ogg().  The rest
224       * of the calls work the same as in the C layer.
225       *
226       * There are no mandatory callbacks; all the callbacks from
227       * FLAC::Encoder::Stream are implemented here fully and support
228       * full post-encode STREAMINFO and SEEKTABLE updating.  There is
229       * only an optional progress callback which you may override to
230       * get periodic reports on the progress of the encode.
231       */
232      class FLACPP_API File: public Stream {
233      public:
234         File();
235         virtual ~File();
236
237         virtual ::FLAC__StreamEncoderInitStatus init(FILE *file);                      ///< See FLAC__stream_encoder_init_FILE()
238         virtual ::FLAC__StreamEncoderInitStatus init(const char *filename);            ///< See FLAC__stream_encoder_init_file()
239         virtual ::FLAC__StreamEncoderInitStatus init(const std::string &filename);     ///< See FLAC__stream_encoder_init_file()
240         virtual ::FLAC__StreamEncoderInitStatus init_ogg(FILE *file);                  ///< See FLAC__stream_encoder_init_ogg_FILE()
241         virtual ::FLAC__StreamEncoderInitStatus init_ogg(const char *filename);        ///< See FLAC__stream_encoder_init_ogg_file()
242         virtual ::FLAC__StreamEncoderInitStatus init_ogg(const std::string &filename); ///< See FLAC__stream_encoder_init_ogg_file()
243      protected:
244         /// See FLAC__StreamEncoderProgressCallback
245         virtual void progress_callback(FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate);
246
247         /// This is a dummy implementation to satisfy the pure virtual in Stream that is actually supplied internally by the C layer
248         virtual ::FLAC__StreamEncoderWriteStatus write_callback(const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame);
249      private:
250         static void progress_callback_(const ::FLAC__StreamEncoder *encoder, FLAC__uint64 bytes_written, FLAC__uint64 samples_written, unsigned frames_written, unsigned total_frames_estimate, void *client_data);
251
252         // Private and undefined so you can't use them:
253         File(const Stream &);
254         void operator=(const Stream &);
255      };
256
257   }
258}
259
260#endif
src/lib/libflac/include/flac++/metadata.h
r0r14135
1/* libFLAC++ - Free Lossless Audio Codec library
2 * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLACPP__METADATA_H
33#define FLACPP__METADATA_H
34
35#include "export.h"
36
37#include "flac/metadata.h"
38
39// ===============================================================
40//
41//  Full documentation for the metadata interface can be found
42//  in the C layer in include/FLAC/metadata.h
43//
44// ===============================================================
45
46/** \file include/FLAC++/metadata.h
47 *
48 *  \brief
49 *  This module provides classes for creating and manipulating FLAC
50 *  metadata blocks in memory, and three progressively more powerful
51 *  interfaces for traversing and editing metadata in FLAC files.
52 *
53 *  See the detailed documentation for each interface in the
54 *  \link flacpp_metadata metadata \endlink module.
55 */
56
57/** \defgroup flacpp_metadata FLAC++/metadata.h: metadata interfaces
58 *  \ingroup flacpp
59 *
60 *  \brief
61 *  This module provides classes for creating and manipulating FLAC
62 *  metadata blocks in memory, and three progressively more powerful
63 *  interfaces for traversing and editing metadata in FLAC files.
64 *
65 *  The behavior closely mimics the C layer interface; be sure to read
66 *  the detailed description of the
67 *  \link flac_metadata C metadata module \endlink.  Note that like the
68 *  C layer, currently only the Chain interface (level 2) supports Ogg
69 *  FLAC files, and it is read-only i.e. no writing back changed
70 *  metadata to file.
71 */
72
73
74namespace FLAC {
75   namespace Metadata {
76
77      // ============================================================
78      //
79      //  Metadata objects
80      //
81      // ============================================================
82
83      /** \defgroup flacpp_metadata_object FLAC++/metadata.h: metadata object classes
84       *  \ingroup flacpp_metadata
85       *
86       * This module contains classes representing FLAC metadata
87       * blocks in memory.
88       *
89       * The behavior closely mimics the C layer interface; be
90       * sure to read the detailed description of the
91       * \link flac_metadata_object C metadata object module \endlink.
92       *
93       * Any time a metadata object is constructed or assigned, you
94       * should check is_valid() to make sure the underlying
95       * ::FLAC__StreamMetadata object was able to be created.
96       *
97       * \warning
98       * When the get_*() methods of any metadata object method
99       * return you a const pointer, DO NOT disobey and write into it.
100       * Always use the set_*() methods.
101       *
102       * \{
103       */
104
105      /** Base class for all metadata block types.
106       *  See the \link flacpp_metadata_object overview \endlink for more.
107       */
108      class FLACPP_API Prototype {
109      protected:
110         //@{
111         /** Constructs a copy of the given object.  This form
112          *  always performs a deep copy.
113          */
114         Prototype(const Prototype &);
115         Prototype(const ::FLAC__StreamMetadata &);
116         Prototype(const ::FLAC__StreamMetadata *);
117         //@}
118
119         /** Constructs an object with copy control.  When \a copy
120          *  is \c true, behaves identically to
121          *  FLAC::Metadata::Prototype::Prototype(const ::FLAC__StreamMetadata *object).
122          *  When \a copy is \c false, the instance takes ownership of
123          *  the pointer and the ::FLAC__StreamMetadata object will
124          *  be freed by the destructor.
125          *
126          *  \assert
127          *    \code object != NULL \endcode
128          */
129         Prototype(::FLAC__StreamMetadata *object, bool copy);
130
131         //@{
132         /** Assign from another object.  Always performs a deep copy. */
133         Prototype &operator=(const Prototype &);
134         Prototype &operator=(const ::FLAC__StreamMetadata &);
135         Prototype &operator=(const ::FLAC__StreamMetadata *);
136         //@}
137
138         /** Assigns an object with copy control.  See
139          *  Prototype(::FLAC__StreamMetadata *object, bool copy).
140          */
141         Prototype &assign_object(::FLAC__StreamMetadata *object, bool copy);
142
143         /** Deletes the underlying ::FLAC__StreamMetadata object.
144          */
145         virtual void clear();
146
147         ::FLAC__StreamMetadata *object_;
148      public:
149         /** Deletes the underlying ::FLAC__StreamMetadata object.
150          */
151         virtual ~Prototype();
152
153         //@{
154         /** Check for equality, performing a deep compare by following pointers.
155          */
156         inline bool operator==(const Prototype &) const;
157         inline bool operator==(const ::FLAC__StreamMetadata &) const;
158         inline bool operator==(const ::FLAC__StreamMetadata *) const;
159         //@}
160
161         //@{
162         /** Check for inequality, performing a deep compare by following pointers. */
163         inline bool operator!=(const Prototype &) const;
164         inline bool operator!=(const ::FLAC__StreamMetadata &) const;
165         inline bool operator!=(const ::FLAC__StreamMetadata *) const;
166         //@}
167
168         friend class SimpleIterator;
169         friend class Iterator;
170
171         /** Returns \c true if the object was correctly constructed
172          *  (i.e. the underlying ::FLAC__StreamMetadata object was
173          *  properly allocated), else \c false.
174          */
175         inline bool is_valid() const;
176
177         /** Returns \c true if this block is the last block in a
178          *  stream, else \c false.
179          *
180          * \assert
181          *   \code is_valid() \endcode
182          */
183         bool get_is_last() const;
184
185         /** Returns the type of the block.
186          *
187          * \assert
188          *   \code is_valid() \endcode
189          */
190         ::FLAC__MetadataType get_type() const;
191
192         /** Returns the stream length of the metadata block.
193          *
194          * \note
195          *   The length does not include the metadata block header,
196          *   per spec.
197          *
198          * \assert
199          *   \code is_valid() \endcode
200          */
201         unsigned get_length() const;
202
203         /** Sets the "is_last" flag for the block.  When using the iterators
204          *  it is not necessary to set this flag; they will do it for you.
205          *
206          * \assert
207          *   \code is_valid() \endcode
208          */
209         void set_is_last(bool);
210
211         /** Returns a pointer to the underlying ::FLAC__StreamMetadata
212          *  object.  This can be useful for plugging any holes between
213          *  the C++ and C interfaces.
214          *
215          * \assert
216          *   \code is_valid() \endcode
217          */
218         inline operator const ::FLAC__StreamMetadata *() const;
219      private:
220         /** Private and undefined so you can't use it. */
221         Prototype();
222
223         // These are used only by Iterator
224         bool is_reference_;
225         inline void set_reference(bool x) { is_reference_ = x; }
226      };
227
228#ifdef _MSC_VER
229// warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning)
230#pragma warning ( disable : 4800 )
231#endif
232
233      inline bool Prototype::operator==(const Prototype &object) const
234      { return (bool)::FLAC__metadata_object_is_equal(object_, object.object_); }
235
236      inline bool Prototype::operator==(const ::FLAC__StreamMetadata &object) const
237      { return (bool)::FLAC__metadata_object_is_equal(object_, &object); }
238
239      inline bool Prototype::operator==(const ::FLAC__StreamMetadata *object) const
240      { return (bool)::FLAC__metadata_object_is_equal(object_, object); }
241
242#ifdef _MSC_VER
243// @@@ how to re-enable?  the following doesn't work
244// #pragma warning ( enable : 4800 )
245#endif
246
247      inline bool Prototype::operator!=(const Prototype &object) const
248      { return !operator==(object); }
249
250      inline bool Prototype::operator!=(const ::FLAC__StreamMetadata &object) const
251      { return !operator==(object); }
252
253      inline bool Prototype::operator!=(const ::FLAC__StreamMetadata *object) const
254      { return !operator==(object); }
255
256      inline bool Prototype::is_valid() const
257      { return 0 != object_; }
258
259      inline Prototype::operator const ::FLAC__StreamMetadata *() const
260      { return object_; }
261
262      /** Create a deep copy of an object and return it. */
263      FLACPP_API Prototype *clone(const Prototype *);
264
265
266      /** STREAMINFO metadata block.
267       *  See the \link flacpp_metadata_object overview \endlink for more,
268       *  and the <A HREF="../format.html#metadata_block_streaminfo">format specification</A>.
269       */
270      class FLACPP_API StreamInfo : public Prototype {
271      public:
272         StreamInfo();
273
274         //@{
275         /** Constructs a copy of the given object.  This form
276          *  always performs a deep copy.
277          */
278         inline StreamInfo(const StreamInfo &object): Prototype(object) { }
279         inline StreamInfo(const ::FLAC__StreamMetadata &object): Prototype(object) { }
280         inline StreamInfo(const ::FLAC__StreamMetadata *object): Prototype(object) { }
281         //@}
282
283         /** Constructs an object with copy control.  See
284          *  Prototype(::FLAC__StreamMetadata *object, bool copy).
285          */
286         inline StreamInfo(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { }
287
288         ~StreamInfo();
289
290         //@{
291         /** Assign from another object.  Always performs a deep copy. */
292         inline StreamInfo &operator=(const StreamInfo &object) { Prototype::operator=(object); return *this; }
293         inline StreamInfo &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; }
294         inline StreamInfo &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; }
295         //@}
296
297         /** Assigns an object with copy control.  See
298          *  Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy).
299          */
300         inline StreamInfo &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; }
301
302         //@{
303         /** Check for equality, performing a deep compare by following pointers. */
304         inline bool operator==(const StreamInfo &object) const { return Prototype::operator==(object); }
305         inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); }
306         inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); }
307         //@}
308
309         //@{
310         /** Check for inequality, performing a deep compare by following pointers. */
311         inline bool operator!=(const StreamInfo &object) const { return Prototype::operator!=(object); }
312         inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); }
313         inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); }
314         //@}
315
316         //@{
317         /** See <A HREF="../format.html#metadata_block_streaminfo">format specification</A>. */
318         unsigned get_min_blocksize() const;
319         unsigned get_max_blocksize() const;
320         unsigned get_min_framesize() const;
321         unsigned get_max_framesize() const;
322         unsigned get_sample_rate() const;
323         unsigned get_channels() const;
324         unsigned get_bits_per_sample() const;
325         FLAC__uint64 get_total_samples() const;
326         const FLAC__byte *get_md5sum() const;
327
328         void set_min_blocksize(unsigned value);
329         void set_max_blocksize(unsigned value);
330         void set_min_framesize(unsigned value);
331         void set_max_framesize(unsigned value);
332         void set_sample_rate(unsigned value);
333         void set_channels(unsigned value);
334         void set_bits_per_sample(unsigned value);
335         void set_total_samples(FLAC__uint64 value);
336         void set_md5sum(const FLAC__byte value[16]);
337         //@}
338      };
339
340      /** PADDING metadata block.
341       *  See the \link flacpp_metadata_object overview \endlink for more,
342       *  and the <A HREF="../format.html#metadata_block_padding">format specification</A>.
343       */
344      class FLACPP_API Padding : public Prototype {
345      public:
346         Padding();
347
348         //@{
349         /** Constructs a copy of the given object.  This form
350          *  always performs a deep copy.
351          */
352         inline Padding(const Padding &object): Prototype(object) { }
353         inline Padding(const ::FLAC__StreamMetadata &object): Prototype(object) { }
354         inline Padding(const ::FLAC__StreamMetadata *object): Prototype(object) { }
355         //@}
356
357         /** Constructs an object with copy control.  See
358          *  Prototype(::FLAC__StreamMetadata *object, bool copy).
359          */
360         inline Padding(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { }
361
362         ~Padding();
363
364         //@{
365         /** Assign from another object.  Always performs a deep copy. */
366         inline Padding &operator=(const Padding &object) { Prototype::operator=(object); return *this; }
367         inline Padding &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; }
368         inline Padding &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; }
369         //@}
370
371         /** Assigns an object with copy control.  See
372          *  Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy).
373          */
374         inline Padding &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; }
375
376         //@{
377         /** Check for equality, performing a deep compare by following pointers. */
378         inline bool operator==(const Padding &object) const { return Prototype::operator==(object); }
379         inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); }
380         inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); }
381         //@}
382
383         //@{
384         /** Check for inequality, performing a deep compare by following pointers. */
385         inline bool operator!=(const Padding &object) const { return Prototype::operator!=(object); }
386         inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); }
387         inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); }
388         //@}
389
390         void set_length(unsigned length);
391      };
392
393      /** APPLICATION metadata block.
394       *  See the \link flacpp_metadata_object overview \endlink for more,
395       *  and the <A HREF="../format.html#metadata_block_application">format specification</A>.
396       */
397      class FLACPP_API Application : public Prototype {
398      public:
399         Application();
400         //
401         //@{
402         /** Constructs a copy of the given object.  This form
403          *  always performs a deep copy.
404          */
405         inline Application(const Application &object): Prototype(object) { }
406         inline Application(const ::FLAC__StreamMetadata &object): Prototype(object) { }
407         inline Application(const ::FLAC__StreamMetadata *object): Prototype(object) { }
408         //@}
409
410         /** Constructs an object with copy control.  See
411          *  Prototype(::FLAC__StreamMetadata *object, bool copy).
412          */
413         inline Application(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { }
414
415         ~Application();
416
417         //@{
418         /** Assign from another object.  Always performs a deep copy. */
419         inline Application &operator=(const Application &object) { Prototype::operator=(object); return *this; }
420         inline Application &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; }
421         inline Application &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; }
422         //@}
423
424         /** Assigns an object with copy control.  See
425          *  Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy).
426          */
427         inline Application &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; }
428
429         //@{
430         /** Check for equality, performing a deep compare by following pointers. */
431         inline bool operator==(const Application &object) const { return Prototype::operator==(object); }
432         inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); }
433         inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); }
434         //@}
435
436         //@{
437         /** Check for inequality, performing a deep compare by following pointers. */
438         inline bool operator!=(const Application &object) const { return Prototype::operator!=(object); }
439         inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); }
440         inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); }
441         //@}
442
443         const FLAC__byte *get_id() const;
444         const FLAC__byte *get_data() const;
445
446         void set_id(const FLAC__byte value[4]);
447         //! This form always copies \a data
448         bool set_data(const FLAC__byte *data, unsigned length);
449         bool set_data(FLAC__byte *data, unsigned length, bool copy);
450      };
451
452      /** SEEKTABLE metadata block.
453       *  See the \link flacpp_metadata_object overview \endlink for more,
454       *  and the <A HREF="../format.html#metadata_block_seektable">format specification</A>.
455       */
456      class FLACPP_API SeekTable : public Prototype {
457      public:
458         SeekTable();
459
460         //@{
461         /** Constructs a copy of the given object.  This form
462          *  always performs a deep copy.
463          */
464         inline SeekTable(const SeekTable &object): Prototype(object) { }
465         inline SeekTable(const ::FLAC__StreamMetadata &object): Prototype(object) { }
466         inline SeekTable(const ::FLAC__StreamMetadata *object): Prototype(object) { }
467         //@}
468
469         /** Constructs an object with copy control.  See
470          *  Prototype(::FLAC__StreamMetadata *object, bool copy).
471          */
472         inline SeekTable(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { }
473
474         ~SeekTable();
475
476         //@{
477         /** Assign from another object.  Always performs a deep copy. */
478         inline SeekTable &operator=(const SeekTable &object) { Prototype::operator=(object); return *this; }
479         inline SeekTable &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; }
480         inline SeekTable &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; }
481         //@}
482
483         /** Assigns an object with copy control.  See
484          *  Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy).
485          */
486         inline SeekTable &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; }
487
488         //@{
489         /** Check for equality, performing a deep compare by following pointers. */
490         inline bool operator==(const SeekTable &object) const { return Prototype::operator==(object); }
491         inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); }
492         inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); }
493         //@}
494
495         //@{
496         /** Check for inequality, performing a deep compare by following pointers. */
497         inline bool operator!=(const SeekTable &object) const { return Prototype::operator!=(object); }
498         inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); }
499         inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); }
500         //@}
501
502         unsigned get_num_points() const;
503         ::FLAC__StreamMetadata_SeekPoint get_point(unsigned index) const;
504
505         //! See FLAC__metadata_object_seektable_set_point()
506         void set_point(unsigned index, const ::FLAC__StreamMetadata_SeekPoint &point);
507
508         //! See FLAC__metadata_object_seektable_insert_point()
509         bool insert_point(unsigned index, const ::FLAC__StreamMetadata_SeekPoint &point);
510
511         //! See FLAC__metadata_object_seektable_delete_point()
512         bool delete_point(unsigned index);
513
514         //! See FLAC__metadata_object_seektable_is_legal()
515         bool is_legal() const;
516      };
517
518      /** VORBIS_COMMENT metadata block.
519       *  See the \link flacpp_metadata_object overview \endlink for more,
520       *  and the <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>.
521       */
522      class FLACPP_API VorbisComment : public Prototype {
523      public:
524         /** Convenience class for encapsulating Vorbis comment
525          *  entries.  An entry is a vendor string or a comment
526          *  field.  In the case of a vendor string, the field
527          *  name is undefined; only the field value is relevant.
528          *
529          *  A \a field as used in the methods refers to an
530          *  entire 'NAME=VALUE' string; for convenience the
531          *  string is NUL-terminated.  A length field is
532          *  required in the unlikely event that the value
533          *  contains contain embedded NULs.
534          *
535          *  A \a field_name is what is on the left side of the
536          *  first '=' in the \a field.  By definition it is ASCII
537          *  and so is NUL-terminated and does not require a
538          *  length to describe it.  \a field_name is undefined
539          *  for a vendor string entry.
540          *
541          *  A \a field_value is what is on the right side of the
542          *  first '=' in the \a field.  By definition, this may
543          *  contain embedded NULs and so a \a field_value_length
544          *  is required to describe it.  However in practice,
545          *  embedded NULs are not known to be used, so it is
546          *  generally safe to treat field values as NUL-
547          *  terminated UTF-8 strings.
548          *
549          *  Always check is_valid() after the constructor or operator=
550          *  to make sure memory was properly allocated and that the
551          *  Entry conforms to the Vorbis comment specification.
552          */
553         class FLACPP_API Entry {
554         public:
555            Entry();
556
557            Entry(const char *field, unsigned field_length);
558            Entry(const char *field); // assumes \a field is NUL-terminated
559
560            Entry(const char *field_name, const char *field_value, unsigned field_value_length);
561            Entry(const char *field_name, const char *field_value); // assumes \a field_value is NUL-terminated
562
563            Entry(const Entry &entry);
564
565            Entry &operator=(const Entry &entry);
566
567            virtual ~Entry();
568
569            virtual bool is_valid() const; ///< Returns \c true iff object was properly constructed.
570
571            unsigned get_field_length() const;
572            unsigned get_field_name_length() const;
573            unsigned get_field_value_length() const;
574
575            ::FLAC__StreamMetadata_VorbisComment_Entry get_entry() const;
576            const char *get_field() const;
577            const char *get_field_name() const;
578            const char *get_field_value() const;
579
580            bool set_field(const char *field, unsigned field_length);
581            bool set_field(const char *field); // assumes \a field is NUL-terminated
582            bool set_field_name(const char *field_name);
583            bool set_field_value(const char *field_value, unsigned field_value_length);
584            bool set_field_value(const char *field_value); // assumes \a field_value is NUL-terminated
585         protected:
586            bool is_valid_;
587            ::FLAC__StreamMetadata_VorbisComment_Entry entry_;
588            char *field_name_;
589            unsigned field_name_length_;
590            char *field_value_;
591            unsigned field_value_length_;
592         private:
593            void zero();
594            void clear();
595            void clear_entry();
596            void clear_field_name();
597            void clear_field_value();
598            void construct(const char *field, unsigned field_length);
599            void construct(const char *field); // assumes \a field is NUL-terminated
600            void construct(const char *field_name, const char *field_value, unsigned field_value_length);
601            void construct(const char *field_name, const char *field_value); // assumes \a field_value is NUL-terminated
602            void compose_field();
603            void parse_field();
604         };
605
606         VorbisComment();
607
608         //@{
609         /** Constructs a copy of the given object.  This form
610          *  always performs a deep copy.
611          */
612         inline VorbisComment(const VorbisComment &object): Prototype(object) { }
613         inline VorbisComment(const ::FLAC__StreamMetadata &object): Prototype(object) { }
614         inline VorbisComment(const ::FLAC__StreamMetadata *object): Prototype(object) { }
615         //@}
616
617         /** Constructs an object with copy control.  See
618          *  Prototype(::FLAC__StreamMetadata *object, bool copy).
619          */
620         inline VorbisComment(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { }
621
622         ~VorbisComment();
623
624         //@{
625         /** Assign from another object.  Always performs a deep copy. */
626         inline VorbisComment &operator=(const VorbisComment &object) { Prototype::operator=(object); return *this; }
627         inline VorbisComment &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; }
628         inline VorbisComment &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; }
629         //@}
630
631         /** Assigns an object with copy control.  See
632          *  Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy).
633          */
634         inline VorbisComment &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; }
635
636         //@{
637         /** Check for equality, performing a deep compare by following pointers. */
638         inline bool operator==(const VorbisComment &object) const { return Prototype::operator==(object); }
639         inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); }
640         inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); }
641         //@}
642
643         //@{
644         /** Check for inequality, performing a deep compare by following pointers. */
645         inline bool operator!=(const VorbisComment &object) const { return Prototype::operator!=(object); }
646         inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); }
647         inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); }
648         //@}
649
650         unsigned get_num_comments() const;
651         const FLAC__byte *get_vendor_string() const; // NUL-terminated UTF-8 string
652         Entry get_comment(unsigned index) const;
653
654         //! See FLAC__metadata_object_vorbiscomment_set_vendor_string()
655         bool set_vendor_string(const FLAC__byte *string); // NUL-terminated UTF-8 string
656
657         //! See FLAC__metadata_object_vorbiscomment_set_comment()
658         bool set_comment(unsigned index, const Entry &entry);
659
660         //! See FLAC__metadata_object_vorbiscomment_insert_comment()
661         bool insert_comment(unsigned index, const Entry &entry);
662
663         //! See FLAC__metadata_object_vorbiscomment_append_comment()
664         bool append_comment(const Entry &entry);
665
666         //! See FLAC__metadata_object_vorbiscomment_delete_comment()
667         bool delete_comment(unsigned index);
668      };
669
670      /** CUESHEET metadata block.
671       *  See the \link flacpp_metadata_object overview \endlink for more,
672       *  and the <A HREF="../format.html#metadata_block_cuesheet">format specification</A>.
673       */
674      class FLACPP_API CueSheet : public Prototype {
675      public:
676         /** Convenience class for encapsulating a cue sheet
677          *  track.
678          *
679          *  Always check is_valid() after the constructor or operator=
680          *  to make sure memory was properly allocated.
681          */
682         class FLACPP_API Track {
683         protected:
684            ::FLAC__StreamMetadata_CueSheet_Track *object_;
685         public:
686            Track();
687            Track(const ::FLAC__StreamMetadata_CueSheet_Track *track);
688            Track(const Track &track);
689            Track &operator=(const Track &track);
690
691            virtual ~Track();
692
693            virtual bool is_valid() const; ///< Returns \c true iff object was properly constructed.
694
695
696            inline FLAC__uint64 get_offset() const { return object_->offset; }
697            inline FLAC__byte get_number() const { return object_->number; }
698            inline const char *get_isrc() const { return object_->isrc; }
699            inline unsigned get_type() const { return object_->type; }
700            inline bool get_pre_emphasis() const { return object_->pre_emphasis; }
701
702            inline FLAC__byte get_num_indices() const { return object_->num_indices; }
703            ::FLAC__StreamMetadata_CueSheet_Index get_index(unsigned i) const;
704
705            inline const ::FLAC__StreamMetadata_CueSheet_Track *get_track() const { return object_; }
706
707            inline void set_offset(FLAC__uint64 value) { object_->offset = value; }
708            inline void set_number(FLAC__byte value) { object_->number = value; }
709            void set_isrc(const char value[12]);
710            void set_type(unsigned value);
711            inline void set_pre_emphasis(bool value) { object_->pre_emphasis = value? 1 : 0; }
712
713             void set_index(unsigned i, const ::FLAC__StreamMetadata_CueSheet_Index &index);
714            //@@@ It's awkward but to insert/delete index points
715            //@@@ you must use the routines in the CueSheet class.
716         };
717
718         CueSheet();
719
720         //@{
721         /** Constructs a copy of the given object.  This form
722          *  always performs a deep copy.
723          */
724         inline CueSheet(const CueSheet &object): Prototype(object) { }
725         inline CueSheet(const ::FLAC__StreamMetadata &object): Prototype(object) { }
726         inline CueSheet(const ::FLAC__StreamMetadata *object): Prototype(object) { }
727         //@}
728
729         /** Constructs an object with copy control.  See
730          *  Prototype(::FLAC__StreamMetadata *object, bool copy).
731          */
732         inline CueSheet(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { }
733
734         ~CueSheet();
735
736         //@{
737         /** Assign from another object.  Always performs a deep copy. */
738         inline CueSheet &operator=(const CueSheet &object) { Prototype::operator=(object); return *this; }
739         inline CueSheet &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; }
740         inline CueSheet &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; }
741         //@}
742
743         /** Assigns an object with copy control.  See
744          *  Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy).
745          */
746         inline CueSheet &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; }
747
748         //@{
749         /** Check for equality, performing a deep compare by following pointers. */
750         inline bool operator==(const CueSheet &object) const { return Prototype::operator==(object); }
751         inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); }
752         inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); }
753         //@}
754
755         //@{
756         /** Check for inequality, performing a deep compare by following pointers. */
757         inline bool operator!=(const CueSheet &object) const { return Prototype::operator!=(object); }
758         inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); }
759         inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); }
760         //@}
761
762         const char *get_media_catalog_number() const;
763         FLAC__uint64 get_lead_in() const;
764         bool get_is_cd() const;
765
766         unsigned get_num_tracks() const;
767         Track get_track(unsigned i) const;
768
769         void set_media_catalog_number(const char value[128]);
770         void set_lead_in(FLAC__uint64 value);
771         void set_is_cd(bool value);
772
773         void set_index(unsigned track_num, unsigned index_num, const ::FLAC__StreamMetadata_CueSheet_Index &index);
774
775         //! See FLAC__metadata_object_cuesheet_track_insert_index()
776         bool insert_index(unsigned track_num, unsigned index_num, const ::FLAC__StreamMetadata_CueSheet_Index &index);
777
778         //! See FLAC__metadata_object_cuesheet_track_delete_index()
779         bool delete_index(unsigned track_num, unsigned index_num);
780
781         //! See FLAC__metadata_object_cuesheet_set_track()
782         bool set_track(unsigned i, const Track &track);
783
784         //! See FLAC__metadata_object_cuesheet_insert_track()
785         bool insert_track(unsigned i, const Track &track);
786
787         //! See FLAC__metadata_object_cuesheet_delete_track()
788         bool delete_track(unsigned i);
789
790         //! See FLAC__metadata_object_cuesheet_is_legal()
791         bool is_legal(bool check_cd_da_subset = false, const char **violation = 0) const;
792
793         //! See FLAC__metadata_object_cuesheet_calculate_cddb_id()
794         FLAC__uint32 calculate_cddb_id() const;
795      };
796
797      /** PICTURE metadata block.
798       *  See the \link flacpp_metadata_object overview \endlink for more,
799       *  and the <A HREF="../format.html#metadata_block_picture">format specification</A>.
800       */
801      class FLACPP_API Picture : public Prototype {
802      public:
803         Picture();
804
805         //@{
806         /** Constructs a copy of the given object.  This form
807          *  always performs a deep copy.
808          */
809         inline Picture(const Picture &object): Prototype(object) { }
810         inline Picture(const ::FLAC__StreamMetadata &object): Prototype(object) { }
811         inline Picture(const ::FLAC__StreamMetadata *object): Prototype(object) { }
812         //@}
813
814         /** Constructs an object with copy control.  See
815          *  Prototype(::FLAC__StreamMetadata *object, bool copy).
816          */
817         inline Picture(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { }
818
819         ~Picture();
820
821         //@{
822         /** Assign from another object.  Always performs a deep copy. */
823         inline Picture &operator=(const Picture &object) { Prototype::operator=(object); return *this; }
824         inline Picture &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; }
825         inline Picture &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; }
826         //@}
827
828         /** Assigns an object with copy control.  See
829          *  Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy).
830          */
831         inline Picture &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; }
832
833         //@{
834         /** Check for equality, performing a deep compare by following pointers. */
835         inline bool operator==(const Picture &object) const { return Prototype::operator==(object); }
836         inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); }
837         inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); }
838         //@}
839
840         //@{
841         /** Check for inequality, performing a deep compare by following pointers. */
842         inline bool operator!=(const Picture &object) const { return Prototype::operator!=(object); }
843         inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); }
844         inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); }
845         //@}
846
847         ::FLAC__StreamMetadata_Picture_Type get_type() const;
848         const char *get_mime_type() const; // NUL-terminated printable ASCII string
849         const FLAC__byte *get_description() const; // NUL-terminated UTF-8 string
850         FLAC__uint32 get_width() const;
851         FLAC__uint32 get_height() const;
852         FLAC__uint32 get_depth() const;
853         FLAC__uint32 get_colors() const; ///< a return value of \c 0 means true-color, i.e. 2^depth colors
854         FLAC__uint32 get_data_length() const;
855         const FLAC__byte *get_data() const;
856
857         void set_type(::FLAC__StreamMetadata_Picture_Type type);
858
859         //! See FLAC__metadata_object_picture_set_mime_type()
860         bool set_mime_type(const char *string); // NUL-terminated printable ASCII string
861
862         //! See FLAC__metadata_object_picture_set_description()
863         bool set_description(const FLAC__byte *string); // NUL-terminated UTF-8 string
864
865         void set_width(FLAC__uint32 value) const;
866         void set_height(FLAC__uint32 value) const;
867         void set_depth(FLAC__uint32 value) const;
868         void set_colors(FLAC__uint32 value) const; ///< a value of \c 0 means true-color, i.e. 2^depth colors
869
870         //! See FLAC__metadata_object_picture_set_data()
871         bool set_data(const FLAC__byte *data, FLAC__uint32 data_length);
872      };
873
874      /** Opaque metadata block for storing unknown types.
875       *  This should not be used unless you know what you are doing;
876       *  it is currently used only internally to support forward
877       *  compatibility of metadata blocks.
878       *  See the \link flacpp_metadata_object overview \endlink for more,
879       */
880      class FLACPP_API Unknown : public Prototype {
881      public:
882         Unknown();
883         //
884         //@{
885         /** Constructs a copy of the given object.  This form
886          *  always performs a deep copy.
887          */
888         inline Unknown(const Unknown &object): Prototype(object) { }
889         inline Unknown(const ::FLAC__StreamMetadata &object): Prototype(object) { }
890         inline Unknown(const ::FLAC__StreamMetadata *object): Prototype(object) { }
891         //@}
892
893         /** Constructs an object with copy control.  See
894          *  Prototype(::FLAC__StreamMetadata *object, bool copy).
895          */
896         inline Unknown(::FLAC__StreamMetadata *object, bool copy): Prototype(object, copy) { }
897
898         ~Unknown();
899
900         //@{
901         /** Assign from another object.  Always performs a deep copy. */
902         inline Unknown &operator=(const Unknown &object) { Prototype::operator=(object); return *this; }
903         inline Unknown &operator=(const ::FLAC__StreamMetadata &object) { Prototype::operator=(object); return *this; }
904         inline Unknown &operator=(const ::FLAC__StreamMetadata *object) { Prototype::operator=(object); return *this; }
905         //@}
906
907         /** Assigns an object with copy control.  See
908          *  Prototype::assign_object(::FLAC__StreamMetadata *object, bool copy).
909          */
910         inline Unknown &assign(::FLAC__StreamMetadata *object, bool copy) { Prototype::assign_object(object, copy); return *this; }
911
912         //@{
913         /** Check for equality, performing a deep compare by following pointers. */
914         inline bool operator==(const Unknown &object) const { return Prototype::operator==(object); }
915         inline bool operator==(const ::FLAC__StreamMetadata &object) const { return Prototype::operator==(object); }
916         inline bool operator==(const ::FLAC__StreamMetadata *object) const { return Prototype::operator==(object); }
917         //@}
918
919         //@{
920         /** Check for inequality, performing a deep compare by following pointers. */
921         inline bool operator!=(const Unknown &object) const { return Prototype::operator!=(object); }
922         inline bool operator!=(const ::FLAC__StreamMetadata &object) const { return Prototype::operator!=(object); }
923         inline bool operator!=(const ::FLAC__StreamMetadata *object) const { return Prototype::operator!=(object); }
924         //@}
925
926         const FLAC__byte *get_data() const;
927
928         //! This form always copies \a data
929         bool set_data(const FLAC__byte *data, unsigned length);
930         bool set_data(FLAC__byte *data, unsigned length, bool copy);
931      };
932
933      /* \} */
934
935
936      /** \defgroup flacpp_metadata_level0 FLAC++/metadata.h: metadata level 0 interface
937       *  \ingroup flacpp_metadata
938       *
939       *  \brief
940       *  Level 0 metadata iterators.
941       *
942       *  See the \link flac_metadata_level0 C layer equivalent \endlink
943       *  for more.
944       *
945       * \{
946       */
947
948      FLACPP_API bool get_streaminfo(const char *filename, StreamInfo &streaminfo); ///< See FLAC__metadata_get_streaminfo().
949
950      FLACPP_API bool get_tags(const char *filename, VorbisComment *&tags); ///< See FLAC__metadata_get_tags().
951      FLACPP_API bool get_tags(const char *filename, VorbisComment &tags); ///< See FLAC__metadata_get_tags().
952
953      FLACPP_API bool get_cuesheet(const char *filename, CueSheet *&cuesheet); ///< See FLAC__metadata_get_cuesheet().
954      FLACPP_API bool get_cuesheet(const char *filename, CueSheet &cuesheet); ///< See FLAC__metadata_get_cuesheet().
955
956      FLACPP_API bool get_picture(const char *filename, Picture *&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); ///< See FLAC__metadata_get_picture().
957      FLACPP_API bool get_picture(const char *filename, Picture &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); ///< See FLAC__metadata_get_picture().
958
959      /* \} */
960
961
962      /** \defgroup flacpp_metadata_level1 FLAC++/metadata.h: metadata level 1 interface
963       *  \ingroup flacpp_metadata
964       *
965       *  \brief
966       *  Level 1 metadata iterator.
967       *
968       *  The flow through the iterator in the C++ layer is similar
969       *  to the C layer:
970       *    - Create a SimpleIterator instance
971       *    - Check SimpleIterator::is_valid()
972       *    - Call SimpleIterator::init() and check the return
973       *    - Traverse and/or edit.  Edits are written to file
974       *      immediately.
975       *    - Destroy the SimpleIterator instance
976       *
977       *  The ownership of pointers in the C++ layer follows that in
978       *  the C layer, i.e.
979       *    - The objects returned by get_block() are yours to
980       *      modify, but changes are not reflected in the FLAC file
981       *      until you call set_block().  The objects are also
982       *      yours to delete; they are not automatically deleted
983       *      when passed to set_block() or insert_block_after().
984       *
985       *  See the \link flac_metadata_level1 C layer equivalent \endlink
986       *  for more.
987       *
988       * \{
989       */
990
991      /** This class is a wrapper around the FLAC__metadata_simple_iterator
992       *  structures and methods; see the
993       * \link flacpp_metadata_level1 usage guide \endlink and
994       * ::FLAC__Metadata_SimpleIterator.
995       */
996      class FLACPP_API SimpleIterator {
997      public:
998         /** This class is a wrapper around FLAC__Metadata_SimpleIteratorStatus.
999          */
1000         class FLACPP_API Status {
1001         public:
1002            inline Status(::FLAC__Metadata_SimpleIteratorStatus status): status_(status) { }
1003            inline operator ::FLAC__Metadata_SimpleIteratorStatus() const { return status_; }
1004            inline const char *as_cstring() const { return ::FLAC__Metadata_SimpleIteratorStatusString[status_]; }
1005         protected:
1006            ::FLAC__Metadata_SimpleIteratorStatus status_;
1007         };
1008
1009         SimpleIterator();
1010         virtual ~SimpleIterator();
1011
1012         bool is_valid() const; ///< Returns \c true iff object was properly constructed.
1013
1014         bool init(const char *filename, bool read_only, bool preserve_file_stats); ///< See FLAC__metadata_simple_iterator_init().
1015
1016         Status status();                                                    ///< See FLAC__metadata_simple_iterator_status().
1017         bool is_writable() const;                                           ///< See FLAC__metadata_simple_iterator_is_writable().
1018
1019         bool next();                                                        ///< See FLAC__metadata_simple_iterator_next().
1020         bool prev();                                                        ///< See FLAC__metadata_simple_iterator_prev().
1021         bool is_last() const;                                               ///< See FLAC__metadata_simple_iterator_is_last().
1022
1023         off_t get_block_offset() const;                                     ///< See FLAC__metadata_simple_iterator_get_block_offset().
1024         ::FLAC__MetadataType get_block_type() const;                        ///< See FLAC__metadata_simple_iterator_get_block_type().
1025         unsigned get_block_length() const;                                  ///< See FLAC__metadata_simple_iterator_get_block_length().
1026         bool get_application_id(FLAC__byte *id);                            ///< See FLAC__metadata_simple_iterator_get_application_id().
1027         Prototype *get_block();                                             ///< See FLAC__metadata_simple_iterator_get_block().
1028         bool set_block(Prototype *block, bool use_padding = true);          ///< See FLAC__metadata_simple_iterator_set_block().
1029         bool insert_block_after(Prototype *block, bool use_padding = true); ///< See FLAC__metadata_simple_iterator_insert_block_after().
1030         bool delete_block(bool use_padding = true);                         ///< See FLAC__metadata_simple_iterator_delete_block().
1031
1032      protected:
1033         ::FLAC__Metadata_SimpleIterator *iterator_;
1034         void clear();
1035      };
1036
1037      /* \} */
1038
1039
1040      /** \defgroup flacpp_metadata_level2 FLAC++/metadata.h: metadata level 2 interface
1041       *  \ingroup flacpp_metadata
1042       *
1043       *  \brief
1044       *  Level 2 metadata iterator.
1045       *
1046       *  The flow through the iterator in the C++ layer is similar
1047       *  to the C layer:
1048       *    - Create a Chain instance
1049       *    - Check Chain::is_valid()
1050       *    - Call Chain::read() and check the return
1051       *    - Traverse and/or edit with an Iterator or with
1052       *      Chain::merge_padding() or Chain::sort_padding()
1053       *    - Write changes back to FLAC file with Chain::write()
1054       *    - Destroy the Chain instance
1055       *
1056       *  The ownership of pointers in the C++ layer is slightly
1057       *  different than in the C layer, i.e.
1058       *    - The objects returned by Iterator::get_block() are NOT
1059       *      owned by the iterator and should be deleted by the
1060       *      caller when finished, BUT, when you modify the block,
1061       *      it will directly edit what's in the chain and you do
1062       *      not need to call Iterator::set_block().  However the
1063       *      changes will not be reflected in the FLAC file until
1064       *      the chain is written with Chain::write().
1065       *    - When you pass an object to Iterator::set_block(),
1066       *      Iterator::insert_block_before(), or
1067       *      Iterator::insert_block_after(), the iterator takes
1068       *      ownership of the block and it will be deleted by the
1069       *      chain.
1070       *
1071       *  See the \link flac_metadata_level2 C layer equivalent \endlink
1072       *  for more.
1073       *
1074       * \{
1075       */
1076
1077      /** This class is a wrapper around the FLAC__metadata_chain
1078       *  structures and methods; see the
1079       * \link flacpp_metadata_level2 usage guide \endlink and
1080       * ::FLAC__Metadata_Chain.
1081       */
1082      class FLACPP_API Chain {
1083      public:
1084         /** This class is a wrapper around FLAC__Metadata_ChainStatus.
1085          */
1086         class FLACPP_API Status {
1087         public:
1088            inline Status(::FLAC__Metadata_ChainStatus status): status_(status) { }
1089            inline operator ::FLAC__Metadata_ChainStatus() const { return status_; }
1090            inline const char *as_cstring() const { return ::FLAC__Metadata_ChainStatusString[status_]; }
1091         protected:
1092            ::FLAC__Metadata_ChainStatus status_;
1093         };
1094
1095         Chain();
1096         virtual ~Chain();
1097
1098         friend class Iterator;
1099
1100         bool is_valid() const; ///< Returns \c true iff object was properly constructed.
1101
1102         Status status();                                                ///< See FLAC__metadata_chain_status().
1103
1104         bool read(const char *filename, bool is_ogg = false);                                ///< See FLAC__metadata_chain_read(), FLAC__metadata_chain_read_ogg().
1105         bool read(FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, bool is_ogg = false);  ///< See FLAC__metadata_chain_read_with_callbacks(), FLAC__metadata_chain_read_ogg_with_callbacks().
1106
1107         bool check_if_tempfile_needed(bool use_padding);                ///< See FLAC__metadata_chain_check_if_tempfile_needed().
1108
1109         bool write(bool use_padding = true, bool preserve_file_stats = false); ///< See FLAC__metadata_chain_write().
1110         bool write(bool use_padding, ::FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks); ///< See FLAC__metadata_chain_write_with_callbacks().
1111         bool write(bool use_padding, ::FLAC__IOHandle handle, ::FLAC__IOCallbacks callbacks, ::FLAC__IOHandle temp_handle, ::FLAC__IOCallbacks temp_callbacks); ///< See FLAC__metadata_chain_write_with_callbacks_and_tempfile().
1112
1113         void merge_padding();                                           ///< See FLAC__metadata_chain_merge_padding().
1114         void sort_padding();                                            ///< See FLAC__metadata_chain_sort_padding().
1115
1116      protected:
1117         ::FLAC__Metadata_Chain *chain_;
1118         virtual void clear();
1119      };
1120
1121      /** This class is a wrapper around the FLAC__metadata_iterator
1122       *  structures and methods; see the
1123       * \link flacpp_metadata_level2 usage guide \endlink and
1124       * ::FLAC__Metadata_Iterator.
1125       */
1126      class FLACPP_API Iterator {
1127      public:
1128         Iterator();
1129         virtual ~Iterator();
1130
1131         bool is_valid() const; ///< Returns \c true iff object was properly constructed.
1132
1133
1134         void init(Chain &chain);                       ///< See FLAC__metadata_iterator_init().
1135
1136         bool next();                                   ///< See FLAC__metadata_iterator_next().
1137         bool prev();                                   ///< See FLAC__metadata_iterator_prev().
1138
1139         ::FLAC__MetadataType get_block_type() const;   ///< See FLAC__metadata_iterator_get_block_type().
1140         Prototype *get_block();                        ///< See FLAC__metadata_iterator_get_block().
1141         bool set_block(Prototype *block);              ///< See FLAC__metadata_iterator_set_block().
1142         bool delete_block(bool replace_with_padding);  ///< See FLAC__metadata_iterator_delete_block().
1143         bool insert_block_before(Prototype *block);    ///< See FLAC__metadata_iterator_insert_block_before().
1144         bool insert_block_after(Prototype *block);     ///< See FLAC__metadata_iterator_insert_block_after().
1145
1146      protected:
1147         ::FLAC__Metadata_Iterator *iterator_;
1148         virtual void clear();
1149      };
1150
1151      /* \} */
1152
1153   }
1154}
1155
1156#endif
src/lib/libflac/include/flac++/export.h
r0r14135
1/* libFLAC++ - Free Lossless Audio Codec library
2 * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLACPP__EXPORT_H
33#define FLACPP__EXPORT_H
34
35/** \file include/FLAC++/export.h
36 *
37 *  \brief
38 *  This module contains #defines and symbols for exporting function
39 *  calls, and providing version information and compiled-in features.
40 *
41 *  See the \link flacpp_export export \endlink module.
42 */
43
44/** \defgroup flacpp_export FLAC++/export.h: export symbols
45 *  \ingroup flacpp
46 *
47 *  \brief
48 *  This module contains #defines and symbols for exporting function
49 *  calls, and providing version information and compiled-in features.
50 *
51 *  If you are compiling with MSVC and will link to the static library
52 *  (libFLAC++.lib) you should define FLAC__NO_DLL in your project to
53 *  make sure the symbols are exported properly.
54 *
55 * \{
56 */
57
58#if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
59#define FLACPP_API
60
61#else
62
63#ifdef FLACPP_API_EXPORTS
64#define   FLACPP_API   _declspec(dllexport)
65#else
66#define FLACPP_API   _declspec(dllimport)
67
68#endif
69#endif
70
71/* These #defines will mirror the libtool-based library version number, see
72 * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
73 */
74#define FLACPP_API_VERSION_CURRENT 8
75#define FLACPP_API_VERSION_REVISION 0
76#define FLACPP_API_VERSION_AGE 2
77
78/* \} */
79
80#endif
src/lib/libflac/include/flac++/decoder.h
r0r14135
1/* libFLAC++ - Free Lossless Audio Codec library
2 * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLACPP__DECODER_H
33#define FLACPP__DECODER_H
34
35#include "export.h"
36
37#include <string>
38#include "flac/stream_decoder.h"
39
40
41/** \file include/FLAC++/decoder.h
42 *
43 *  \brief
44 *  This module contains the classes which implement the various
45 *  decoders.
46 *
47 *  See the detailed documentation in the
48 *  \link flacpp_decoder decoder \endlink module.
49 */
50
51/** \defgroup flacpp_decoder FLAC++/decoder.h: decoder classes
52 *  \ingroup flacpp
53 *
54 *  \brief
55 *  This module describes the decoder layers provided by libFLAC++.
56 *
57 * The libFLAC++ decoder classes are object wrappers around their
58 * counterparts in libFLAC.  All decoding layers available in
59 * libFLAC are also provided here.  The interface is very similar;
60 * make sure to read the \link flac_decoder libFLAC decoder module \endlink.
61 *
62 * There are only two significant differences here.  First, instead of
63 * passing in C function pointers for callbacks, you inherit from the
64 * decoder class and provide implementations for the callbacks in your
65 * derived class; because of this there is no need for a 'client_data'
66 * property.
67 *
68 * Second, there are two stream decoder classes.  FLAC::Decoder::Stream
69 * is used for the same cases that FLAC__stream_decoder_init_stream() /
70 * FLAC__stream_decoder_init_ogg_stream() are used, and FLAC::Decoder::File
71 * is used for the same cases that
72 * FLAC__stream_decoder_init_FILE() and FLAC__stream_decoder_init_file() /
73 * FLAC__stream_decoder_init_ogg_FILE() and FLAC__stream_decoder_init_ogg_file()
74 * are used.
75 */
76
77namespace FLAC {
78   namespace Decoder {
79
80      /** \ingroup flacpp_decoder
81       *  \brief
82       *  This class wraps the ::FLAC__StreamDecoder.  If you are
83       *  decoding from a file, FLAC::Decoder::File may be more
84       *  convenient.
85       *
86       * The usage of this class is similar to FLAC__StreamDecoder,
87       * except instead of providing callbacks to
88       * FLAC__stream_decoder_init*_stream(), you will inherit from this
89       * class and override the virtual callback functions with your
90       * own implementations, then call init() or init_ogg().  The rest
91       * of the calls work the same as in the C layer.
92       *
93       * Only the read, write, and error callbacks are mandatory.  The
94       * others are optional; this class provides default
95       * implementations that do nothing.  In order for seeking to work
96       * you must overide seek_callback(), tell_callback(),
97       * length_callback(), and eof_callback().
98       */
99      class FLACPP_API Stream {
100      public:
101         /** This class is a wrapper around FLAC__StreamDecoderState.
102          */
103         class FLACPP_API State {
104         public:
105            inline State(::FLAC__StreamDecoderState state): state_(state) { }
106            inline operator ::FLAC__StreamDecoderState() const { return state_; }
107            inline const char *as_cstring() const { return ::FLAC__StreamDecoderStateString[state_]; }
108            inline const char *resolved_as_cstring(const Stream &decoder) const { return ::FLAC__stream_decoder_get_resolved_state_string(decoder.decoder_); }
109         protected:
110            ::FLAC__StreamDecoderState state_;
111         };
112
113         Stream();
114         virtual ~Stream();
115
116         //@{
117         /** Call after construction to check the that the object was created
118          *  successfully.  If not, use get_state() to find out why not.
119          */
120         virtual bool is_valid() const;
121         inline operator bool() const { return is_valid(); } ///< See is_valid()
122         //@}
123
124         virtual bool set_ogg_serial_number(long value);                        ///< See FLAC__stream_decoder_set_ogg_serial_number()
125         virtual bool set_md5_checking(bool value);                             ///< See FLAC__stream_decoder_set_md5_checking()
126         virtual bool set_metadata_respond(::FLAC__MetadataType type);          ///< See FLAC__stream_decoder_set_metadata_respond()
127         virtual bool set_metadata_respond_application(const FLAC__byte id[4]); ///< See FLAC__stream_decoder_set_metadata_respond_application()
128         virtual bool set_metadata_respond_all();                               ///< See FLAC__stream_decoder_set_metadata_respond_all()
129         virtual bool set_metadata_ignore(::FLAC__MetadataType type);           ///< See FLAC__stream_decoder_set_metadata_ignore()
130         virtual bool set_metadata_ignore_application(const FLAC__byte id[4]);  ///< See FLAC__stream_decoder_set_metadata_ignore_application()
131         virtual bool set_metadata_ignore_all();                                ///< See FLAC__stream_decoder_set_metadata_ignore_all()
132
133         /* get_state() is not virtual since we want subclasses to be able to return their own state */
134         State get_state() const;                                          ///< See FLAC__stream_decoder_get_state()
135         virtual bool get_md5_checking() const;                            ///< See FLAC__stream_decoder_get_md5_checking()
136         virtual FLAC__uint64 get_total_samples() const;                   ///< See FLAC__stream_decoder_get_total_samples()
137         virtual unsigned get_channels() const;                            ///< See FLAC__stream_decoder_get_channels()
138         virtual ::FLAC__ChannelAssignment get_channel_assignment() const; ///< See FLAC__stream_decoder_get_channel_assignment()
139         virtual unsigned get_bits_per_sample() const;                     ///< See FLAC__stream_decoder_get_bits_per_sample()
140         virtual unsigned get_sample_rate() const;                         ///< See FLAC__stream_decoder_get_sample_rate()
141         virtual unsigned get_blocksize() const;                           ///< See FLAC__stream_decoder_get_blocksize()
142         virtual bool get_decode_position(FLAC__uint64 *position) const;   ///< See FLAC__stream_decoder_get_decode_position()
143
144         virtual ::FLAC__StreamDecoderInitStatus init();      ///< Seek FLAC__stream_decoder_init_stream()
145         virtual ::FLAC__StreamDecoderInitStatus init_ogg();  ///< Seek FLAC__stream_decoder_init_ogg_stream()
146
147         virtual bool finish(); ///< See FLAC__stream_decoder_finish()
148
149         virtual bool flush(); ///< See FLAC__stream_decoder_flush()
150         virtual bool reset(); ///< See FLAC__stream_decoder_reset()
151
152         virtual bool process_single();                ///< See FLAC__stream_decoder_process_single()
153         virtual bool process_until_end_of_metadata(); ///< See FLAC__stream_decoder_process_until_end_of_metadata()
154         virtual bool process_until_end_of_stream();   ///< See FLAC__stream_decoder_process_until_end_of_stream()
155         virtual bool skip_single_frame();             ///< See FLAC__stream_decoder_skip_single_frame()
156
157         virtual bool seek_absolute(FLAC__uint64 sample); ///< See FLAC__stream_decoder_seek_absolute()
158      protected:
159         /// see FLAC__StreamDecoderReadCallback
160         virtual ::FLAC__StreamDecoderReadStatus read_callback(FLAC__byte buffer[], size_t *bytes) = 0;
161
162         /// see FLAC__StreamDecoderSeekCallback
163         virtual ::FLAC__StreamDecoderSeekStatus seek_callback(FLAC__uint64 absolute_byte_offset);
164
165         /// see FLAC__StreamDecoderTellCallback
166         virtual ::FLAC__StreamDecoderTellStatus tell_callback(FLAC__uint64 *absolute_byte_offset);
167
168         /// see FLAC__StreamDecoderLengthCallback
169         virtual ::FLAC__StreamDecoderLengthStatus length_callback(FLAC__uint64 *stream_length);
170
171         /// see FLAC__StreamDecoderEofCallback
172         virtual bool eof_callback();
173
174         /// see FLAC__StreamDecoderWriteCallback
175         virtual ::FLAC__StreamDecoderWriteStatus write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) = 0;
176
177         /// see FLAC__StreamDecoderMetadataCallback
178         virtual void metadata_callback(const ::FLAC__StreamMetadata *metadata);
179
180         /// see FLAC__StreamDecoderErrorCallback
181         virtual void error_callback(::FLAC__StreamDecoderErrorStatus status) = 0;
182
183#if (defined _MSC_VER) || (defined __BORLANDC__) || (defined __GNUG__ && (__GNUG__ < 2 || (__GNUG__ == 2 && __GNUC_MINOR__ < 96))) || (defined __SUNPRO_CC)
184         // lame hack: some MSVC/GCC versions can't see a protected decoder_ from nested State::resolved_as_cstring()
185         friend State;
186#endif
187         ::FLAC__StreamDecoder *decoder_;
188
189         static ::FLAC__StreamDecoderReadStatus read_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
190         static ::FLAC__StreamDecoderSeekStatus seek_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
191         static ::FLAC__StreamDecoderTellStatus tell_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
192         static ::FLAC__StreamDecoderLengthStatus length_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
193         static FLAC__bool eof_callback_(const ::FLAC__StreamDecoder *decoder, void *client_data);
194         static ::FLAC__StreamDecoderWriteStatus write_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
195         static void metadata_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *client_data);
196         static void error_callback_(const ::FLAC__StreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *client_data);
197      private:
198         // Private and undefined so you can't use them:
199         Stream(const Stream &);
200         void operator=(const Stream &);
201      };
202
203      /** \ingroup flacpp_decoder
204       *  \brief
205       *  This class wraps the ::FLAC__StreamDecoder.  If you are
206       *  not decoding from a file, you may need to use
207       *  FLAC::Decoder::Stream.
208       *
209       * The usage of this class is similar to FLAC__StreamDecoder,
210       * except instead of providing callbacks to
211       * FLAC__stream_decoder_init*_FILE() or
212       * FLAC__stream_decoder_init*_file(), you will inherit from this
213       * class and override the virtual callback functions with your
214       * own implementations, then call init() or init_off().  The rest
215       * of the calls work the same as in the C layer.
216       *
217       * Only the write, and error callbacks from FLAC::Decoder::Stream
218       * are mandatory.  The others are optional; this class provides
219       * full working implementations for all other callbacks and
220       * supports seeking.
221       */
222      class FLACPP_API File: public Stream {
223      public:
224         File();
225         virtual ~File();
226
227         virtual ::FLAC__StreamDecoderInitStatus init(FILE *file);                      ///< See FLAC__stream_decoder_init_FILE()
228         virtual ::FLAC__StreamDecoderInitStatus init(const char *filename);            ///< See FLAC__stream_decoder_init_file()
229         virtual ::FLAC__StreamDecoderInitStatus init(const std::string &filename);     ///< See FLAC__stream_decoder_init_file()
230         virtual ::FLAC__StreamDecoderInitStatus init_ogg(FILE *file);                  ///< See FLAC__stream_decoder_init_ogg_FILE()
231         virtual ::FLAC__StreamDecoderInitStatus init_ogg(const char *filename);        ///< See FLAC__stream_decoder_init_ogg_file()
232         virtual ::FLAC__StreamDecoderInitStatus init_ogg(const std::string &filename); ///< See FLAC__stream_decoder_init_ogg_file()
233      protected:
234         // this is a dummy implementation to satisfy the pure virtual in Stream that is actually supplied internally by the C layer
235         virtual ::FLAC__StreamDecoderReadStatus read_callback(FLAC__byte buffer[], size_t *bytes);
236      private:
237         // Private and undefined so you can't use them:
238         File(const File &);
239         void operator=(const File &);
240      };
241
242   }
243}
244
245#endif
src/lib/libflac/include/flac++/all.h
r0r14135
1/* libFLAC++ - Free Lossless Audio Codec library
2 * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#ifndef FLACPP__ALL_H
33#define FLACPP__ALL_H
34
35#include "export.h"
36
37#include "encoder.h"
38#include "decoder.h"
39#include "metadata.h"
40
41/** \defgroup flacpp FLAC C++ API
42 *
43 * The FLAC C++ API is the interface to libFLAC++, a set of classes
44 * that encapsulate the encoders, decoders, and metadata interfaces
45 * in libFLAC.
46 */
47
48#endif
src/lib/libflac/libflac.mak
r0r14135
1
2
3
4DEFINES = -DFLAC__NO_ASM -DFLAC__ALIGN_MALLOC_DATA
5
6INCLUDES = -I./include -I$(LIBSRC)/libflac/include
7
8LIBFLACOBJS = \
9   $(LIBOBJ)/libflac/bitmath.o \
10   $(LIBOBJ)/libflac/bitreader.o \
11   $(LIBOBJ)/libflac/bitwriter.o \
12   $(LIBOBJ)/libflac/cpu.o \
13   $(LIBOBJ)/libflac/crc.o \
14   $(LIBOBJ)/libflac/fixed.o \
15   $(LIBOBJ)/libflac/float.o \
16   $(LIBOBJ)/libflac/format.o \
17   $(LIBOBJ)/libflac/lpc.o \
18   $(LIBOBJ)/libflac/md5.o \
19   $(LIBOBJ)/libflac/memory.o \
20   $(LIBOBJ)/libflac/stream_decoder.o \
21   $(LIBOBJ)/libflac/stream_encoder.o \
22   $(LIBOBJ)/libflac/stream_encoder_framing.o \
23   $(LIBOBJ)/libflac/window.o
24
25VERSION=\"1.2.1\"
26CONFIG_CFLAGS=-DHAVE_INTTYPES_H -DHAVE_ICONV  -DFLAC__NO_ASM -D__MINGW32__ -DHAVE_LANGINFO_CODESET -DHAVE_SOCKLEN_T -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
27LIBFLACCFLAGS = -O3 -fomit-frame-pointer -funroll-loops -finline-functions -DNDEBUG $(CONFIG_CFLAGS) $(RELEASE_CFLAGS) -Wno-int-to-pointer-cast -Wno-pointer-to-int-cast -DFLaC__INLINE=__inline__ -DVERSION=$(VERSION) $(DEFINES) $(INCLUDES)
28
29$(LIBOBJ)/libflac/%.o: $(LIBSRC)/libflac/libflac/%.c
30   @echo Compiling $<...
31   $(CC) $(CDEFS) $(LIBFLACCFLAGS) $(CONLYFLAGS) -c $< -o $@
32
33
34$(OBJ)/libflac.a: $(LIBFLACOBJS)
src/lib/libflac/libflac++.mak
r0r14135
1
2
3
4DEFINES = -DFLAC__NO_ASM -DFLAC__ALIGN_MALLOC_DATA
5
6INCLUDES = -I./include -I$(LIBSRC)/libflac/include
7
8LIBFLACPPOBJS = \
9   $(LIBOBJ)/libflacpp/metadata.o \
10   $(LIBOBJ)/libflacpp/stream_decoder.o \
11   $(LIBOBJ)/libflacpp/stream_encoder.o
12
13
14VERSION=\"1.2.1\"
15CONFIG_CFLAGS=-DHAVE_INTTYPES_H -DHAVE_ICONV  -DFLAC__NO_ASM -D__MINGW32__ -DHAVE_LANGINFO_CODESET -DHAVE_SOCKLEN_T -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
16LIBFLACPPCFLAGS = -O3 -fomit-frame-pointer -funroll-loops -finline-functions -DNDEBUG $(CONFIG_CFLAGS) $(RELEASE_CFLAGS) -DFLaC__INLINE=__inline__ -DVERSION=$(VERSION) $(DEFINES) $(INCLUDES)
17
18$(LIBOBJ)/libflacpp/%.o: $(LIBSRC)/libflac/libflac++/%.cpp
19   @echo Compiling $<...
20   $(CC) $(CDEFS) $(LIBFLACPPCFLAGS) $(CPPONLYFLAGS) -c $< -o $@
21
22
23$(OBJ)/libflac++.a: $(LIBFLACPPOBJS)
src/lib/libflac/libflac/fixed.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include <math.h>
37#include <string.h>
38#include "private/bitmath.h"
39#include "private/fixed.h"
40#include "flac/assert.h"
41
42#ifndef M_LN2
43/* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
44#define M_LN2 0.69314718055994530942
45#endif
46
47#ifdef min
48#undef min
49#endif
50#define min(x,y) ((x) < (y)? (x) : (y))
51
52#ifdef local_abs
53#undef local_abs
54#endif
55#define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
56
57#ifdef FLAC__INTEGER_ONLY_LIBRARY
58/* rbps stands for residual bits per sample
59 *
60 *             (ln(2) * err)
61 * rbps = log  (-----------)
62 *           2 (     n     )
63 */
64static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
65{
66   FLAC__uint32 rbps;
67   unsigned bits; /* the number of bits required to represent a number */
68   int fracbits; /* the number of bits of rbps that comprise the fractional part */
69
70   FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
71   FLAC__ASSERT(err > 0);
72   FLAC__ASSERT(n > 0);
73
74   FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
75   if(err <= n)
76      return 0;
77   /*
78    * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
79    * These allow us later to know we won't lose too much precision in the
80    * fixed-point division (err<<fracbits)/n.
81    */
82
83   fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
84
85   err <<= fracbits;
86   err /= n;
87   /* err now holds err/n with fracbits fractional bits */
88
89   /*
90    * Whittle err down to 16 bits max.  16 significant bits is enough for
91    * our purposes.
92    */
93   FLAC__ASSERT(err > 0);
94   bits = FLAC__bitmath_ilog2(err)+1;
95   if(bits > 16) {
96      err >>= (bits-16);
97      fracbits -= (bits-16);
98   }
99   rbps = (FLAC__uint32)err;
100
101   /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
102   rbps *= FLAC__FP_LN2;
103   fracbits += 16;
104   FLAC__ASSERT(fracbits >= 0);
105
106   /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
107   {
108      const int f = fracbits & 3;
109      if(f) {
110         rbps >>= f;
111         fracbits -= f;
112      }
113   }
114
115   rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
116
117   if(rbps == 0)
118      return 0;
119
120   /*
121    * The return value must have 16 fractional bits.  Since the whole part
122    * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
123    * must be >= -3, these assertion allows us to be able to shift rbps
124    * left if necessary to get 16 fracbits without losing any bits of the
125    * whole part of rbps.
126    *
127    * There is a slight chance due to accumulated error that the whole part
128    * will require 6 bits, so we use 6 in the assertion.  Really though as
129    * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
130    */
131   FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
132   FLAC__ASSERT(fracbits >= -3);
133
134   /* now shift the decimal point into place */
135   if(fracbits < 16)
136      return rbps << (16-fracbits);
137   else if(fracbits > 16)
138      return rbps >> (fracbits-16);
139   else
140      return rbps;
141}
142
143static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
144{
145   FLAC__uint32 rbps;
146   unsigned bits; /* the number of bits required to represent a number */
147   int fracbits; /* the number of bits of rbps that comprise the fractional part */
148
149   FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
150   FLAC__ASSERT(err > 0);
151   FLAC__ASSERT(n > 0);
152
153   FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
154   if(err <= n)
155      return 0;
156   /*
157    * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
158    * These allow us later to know we won't lose too much precision in the
159    * fixed-point division (err<<fracbits)/n.
160    */
161
162   fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
163
164   err <<= fracbits;
165   err /= n;
166   /* err now holds err/n with fracbits fractional bits */
167
168   /*
169    * Whittle err down to 16 bits max.  16 significant bits is enough for
170    * our purposes.
171    */
172   FLAC__ASSERT(err > 0);
173   bits = FLAC__bitmath_ilog2_wide(err)+1;
174   if(bits > 16) {
175      err >>= (bits-16);
176      fracbits -= (bits-16);
177   }
178   rbps = (FLAC__uint32)err;
179
180   /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
181   rbps *= FLAC__FP_LN2;
182   fracbits += 16;
183   FLAC__ASSERT(fracbits >= 0);
184
185   /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
186   {
187      const int f = fracbits & 3;
188      if(f) {
189         rbps >>= f;
190         fracbits -= f;
191      }
192   }
193
194   rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
195
196   if(rbps == 0)
197      return 0;
198
199   /*
200    * The return value must have 16 fractional bits.  Since the whole part
201    * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
202    * must be >= -3, these assertion allows us to be able to shift rbps
203    * left if necessary to get 16 fracbits without losing any bits of the
204    * whole part of rbps.
205    *
206    * There is a slight chance due to accumulated error that the whole part
207    * will require 6 bits, so we use 6 in the assertion.  Really though as
208    * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
209    */
210   FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
211   FLAC__ASSERT(fracbits >= -3);
212
213   /* now shift the decimal point into place */
214   if(fracbits < 16)
215      return rbps << (16-fracbits);
216   else if(fracbits > 16)
217      return rbps >> (fracbits-16);
218   else
219      return rbps;
220}
221#endif
222
223#ifndef FLAC__INTEGER_ONLY_LIBRARY
224unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
225#else
226unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
227#endif
228{
229   FLAC__int32 last_error_0 = data[-1];
230   FLAC__int32 last_error_1 = data[-1] - data[-2];
231   FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
232   FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
233   FLAC__int32 error, save;
234   FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
235   unsigned i, order;
236
237   for(i = 0; i < data_len; i++) {
238      error  = data[i]     ; total_error_0 += local_abs(error);                      save = error;
239      error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
240      error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
241      error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
242      error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
243   }
244
245   if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
246      order = 0;
247   else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
248      order = 1;
249   else if(total_error_2 < min(total_error_3, total_error_4))
250      order = 2;
251   else if(total_error_3 < total_error_4)
252      order = 3;
253   else
254      order = 4;
255
256   /* Estimate the expected number of bits per residual signal sample. */
257   /* 'total_error*' is linearly related to the variance of the residual */
258   /* signal, so we use it directly to compute E(|x|) */
259   FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
260   FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
261   FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
262   FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
263   FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
264#ifndef FLAC__INTEGER_ONLY_LIBRARY
265   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);
266   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);
267   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);
268   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);
269   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);
270#else
271   residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
272   residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
273   residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
274   residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
275   residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
276#endif
277
278   return order;
279}
280
281#ifndef FLAC__INTEGER_ONLY_LIBRARY
282unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
283#else
284unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
285#endif
286{
287   FLAC__int32 last_error_0 = data[-1];
288   FLAC__int32 last_error_1 = data[-1] - data[-2];
289   FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
290   FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
291   FLAC__int32 error, save;
292   /* total_error_* are 64-bits to avoid overflow when encoding
293    * erratic signals when the bits-per-sample and blocksize are
294    * large.
295    */
296   FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
297   unsigned i, order;
298
299   for(i = 0; i < data_len; i++) {
300      error  = data[i]     ; total_error_0 += local_abs(error);                      save = error;
301      error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
302      error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
303      error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
304      error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
305   }
306
307   if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
308      order = 0;
309   else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
310      order = 1;
311   else if(total_error_2 < min(total_error_3, total_error_4))
312      order = 2;
313   else if(total_error_3 < total_error_4)
314      order = 3;
315   else
316      order = 4;
317
318   /* Estimate the expected number of bits per residual signal sample. */
319   /* 'total_error*' is linearly related to the variance of the residual */
320   /* signal, so we use it directly to compute E(|x|) */
321   FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
322   FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
323   FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
324   FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
325   FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
326#ifndef FLAC__INTEGER_ONLY_LIBRARY
327#if defined _MSC_VER || defined __MINGW32__
328   /* with MSVC you have to spoon feed it the casting */
329   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);
330   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);
331   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);
332   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);
333   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);
334#else
335   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);
336   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);
337   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);
338   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);
339   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);
340#endif
341#else
342   residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
343   residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
344   residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
345   residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
346   residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
347#endif
348
349   return order;
350}
351
352void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
353{
354   const int idata_len = (int)data_len;
355   int i;
356
357   switch(order) {
358      case 0:
359         FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
360         memcpy(residual, data, sizeof(residual[0])*data_len);
361         break;
362      case 1:
363         for(i = 0; i < idata_len; i++)
364            residual[i] = data[i] - data[i-1];
365         break;
366      case 2:
367         for(i = 0; i < idata_len; i++)
368#if 1 /* OPT: may be faster with some compilers on some systems */
369            residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
370#else
371            residual[i] = data[i] - 2*data[i-1] + data[i-2];
372#endif
373         break;
374      case 3:
375         for(i = 0; i < idata_len; i++)
376#if 1 /* OPT: may be faster with some compilers on some systems */
377            residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
378#else
379            residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
380#endif
381         break;
382      case 4:
383         for(i = 0; i < idata_len; i++)
384#if 1 /* OPT: may be faster with some compilers on some systems */
385            residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
386#else
387            residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
388#endif
389         break;
390      default:
391         FLAC__ASSERT(0);
392   }
393}
394
395void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
396{
397   int i, idata_len = (int)data_len;
398
399   switch(order) {
400      case 0:
401         FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
402         memcpy(data, residual, sizeof(residual[0])*data_len);
403         break;
404      case 1:
405         for(i = 0; i < idata_len; i++)
406            data[i] = residual[i] + data[i-1];
407         break;
408      case 2:
409         for(i = 0; i < idata_len; i++)
410#if 1 /* OPT: may be faster with some compilers on some systems */
411            data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
412#else
413            data[i] = residual[i] + 2*data[i-1] - data[i-2];
414#endif
415         break;
416      case 3:
417         for(i = 0; i < idata_len; i++)
418#if 1 /* OPT: may be faster with some compilers on some systems */
419            data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
420#else
421            data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
422#endif
423         break;
424      case 4:
425         for(i = 0; i < idata_len; i++)
426#if 1 /* OPT: may be faster with some compilers on some systems */
427            data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
428#else
429            data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
430#endif
431         break;
432      default:
433         FLAC__ASSERT(0);
434   }
435}
src/lib/libflac/libflac/bitreader.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36
37#include <stdlib.h> /* for malloc() */
38#include <string.h> /* for memcpy(), memset() */
39
40#include "private/bitmath.h"
41#include "private/bitreader.h"
42#include "private/crc.h"
43#include "flac/assert.h"
44
45/* Things should be fastest when this matches the machine word size */
46/* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
47/* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
48/*           also, some sections currently only have fast versions for 4 or 8 bytes per word */
49typedef FLAC__uint32 brword;
50#define FLAC__BYTES_PER_WORD 4
51#define FLAC__BITS_PER_WORD 32
52#define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
53/* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
54#if WORDS_BIGENDIAN
55#define SWAP_BE_WORD_TO_HOST(x) (x)
56#else
57#ifdef _MSC_VER
58#define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
59#else
60#define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
61#endif
62#endif
63/* counts the # of zero MSBs in a word */
64#define COUNT_ZERO_MSBS(word) ( \
65   (word) <= 0xffff ? \
66      ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
67      ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
68)
69/* this alternate might be slightly faster on some systems/compilers: */
70#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])) )
71
72
73/*
74 * This should be at least twice as large as the largest number of words
75 * required to represent any 'number' (in any encoding) you are going to
76 * read.  With FLAC this is on the order of maybe a few hundred bits.
77 * If the buffer is smaller than that, the decoder won't be able to read
78 * in a whole number that is in a variable length encoding (e.g. Rice).
79 * But to be practical it should be at least 1K bytes.
80 *
81 * Increase this number to decrease the number of read callbacks, at the
82 * expense of using more memory.  Or decrease for the reverse effect,
83 * keeping in mind the limit from the first paragraph.  The optimal size
84 * also depends on the CPU cache size and other factors; some twiddling
85 * may be necessary to squeeze out the best performance.
86 */
87static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
88
89static const unsigned char byte_to_unary_table[] = {
90   8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
91   3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
92   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
93   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
94   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
95   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
96   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
97   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
98   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
100   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
101   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
102   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
103   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
106};
107
108#ifdef min
109#undef min
110#endif
111#define min(x,y) ((x)<(y)?(x):(y))
112#ifdef max
113#undef max
114#endif
115#define max(x,y) ((x)>(y)?(x):(y))
116
117/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
118#ifdef _MSC_VER
119#define FLAC__U64L(x) x
120#else
121#define FLAC__U64L(x) x##LLU
122#endif
123
124#ifndef FLaC__INLINE
125#define FLaC__INLINE
126#endif
127
128/* WATCHOUT: assembly routines rely on the order in which these fields are declared */
129struct FLAC__BitReader {
130   /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
131   /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
132   brword *buffer;
133   unsigned capacity; /* in words */
134   unsigned words; /* # of completed words in buffer */
135   unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
136   unsigned consumed_words; /* #words ... */
137   unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
138   unsigned read_crc16; /* the running frame CRC */
139   unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
140   FLAC__BitReaderReadCallback read_callback;
141   void *client_data;
142   FLAC__CPUInfo cpu_info;
143};
144
145
146static FLAC__uint32 local_swap32_(FLAC__uint32 x)
147{
148   x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
149   return (x>>16) | (x<<16);
150}
151
152#ifdef _MSC_VER
153/* OPT: an MSVC built-in would be better */
154static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
155{
156   __asm {
157      mov edx, start
158      mov ecx, len
159      test ecx, ecx
160loop1:
161      jz done1
162      mov eax, [edx]
163      bswap eax
164      mov [edx], eax
165      add edx, 4
166      dec ecx
167      jmp short loop1
168done1:
169   }
170}
171#endif
172
173static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
174{
175   register unsigned crc = br->read_crc16;
176#if FLAC__BYTES_PER_WORD == 4
177   switch(br->crc16_align) {
178      case  0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
179      case  8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
180      case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
181      case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
182   }
183#elif FLAC__BYTES_PER_WORD == 8
184   switch(br->crc16_align) {
185      case  0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
186      case  8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
187      case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
188      case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
189      case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
190      case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
191      case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
192      case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
193   }
194#else
195   for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
196      crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
197   br->read_crc16 = crc;
198#endif
199   br->crc16_align = 0;
200}
201
202/* would be static except it needs to be called by asm routines */
203FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
204{
205   unsigned start, end;
206   size_t bytes;
207   FLAC__byte *target;
208
209   /* first shift the unconsumed buffer data toward the front as much as possible */
210   if(br->consumed_words > 0) {
211      start = br->consumed_words;
212      end = br->words + (br->bytes? 1:0);
213      memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
214
215      br->words -= start;
216      br->consumed_words = 0;
217   }
218
219   /*
220    * set the target for reading, taking into account word alignment and endianness
221    */
222   bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
223   if(bytes == 0)
224      return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY  */
225   target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
226
227   /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
228    *   bitstream :  11 22 33 44 55            br->words=1 br->bytes=1 (partial tail word is left-justified)
229    *   buffer[BE]:  11 22 33 44 55 ?? ?? ??   (shown layed out as bytes sequentially in memory)
230    *   buffer[LE]:  44 33 22 11 ?? ?? ?? 55   (?? being don't-care)
231    *                               ^^-------target, bytes=3
232    * on LE machines, have to byteswap the odd tail word so nothing is
233    * overwritten:
234    */
235#if WORDS_BIGENDIAN
236#else
237   if(br->bytes)
238      br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
239#endif
240
241   /* now it looks like:
242    *   bitstream :  11 22 33 44 55            br->words=1 br->bytes=1
243    *   buffer[BE]:  11 22 33 44 55 ?? ?? ??
244    *   buffer[LE]:  44 33 22 11 55 ?? ?? ??
245    *                               ^^-------target, bytes=3
246    */
247
248   /* read in the data; note that the callback may return a smaller number of bytes */
249   if(!br->read_callback(target, &bytes, br->client_data))
250      return false;
251
252   /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
253    *   bitstream :  11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
254    *   buffer[BE]:  11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
255    *   buffer[LE]:  44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
256    * now have to byteswap on LE machines:
257    */
258#if WORDS_BIGENDIAN
259#else
260   end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
261# if defined(_MSC_VER) && (FLAC__BYTES_PER_WORD == 4)
262   if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
263      start = br->words;
264      local_swap32_block_(br->buffer + start, end - start);
265   }
266   else
267# endif
268   for(start = br->words; start < end; start++)
269      br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
270#endif
271
272   /* now it looks like:
273    *   bitstream :  11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
274    *   buffer[BE]:  11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
275    *   buffer[LE]:  44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
276    * finally we'll update the reader values:
277    */
278   end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
279   br->words = end / FLAC__BYTES_PER_WORD;
280   br->bytes = end % FLAC__BYTES_PER_WORD;
281
282   return true;
283}
284
285/***********************************************************************
286 *
287 * Class constructor/destructor
288 *
289 ***********************************************************************/
290
291FLAC__BitReader *FLAC__bitreader_new(void)
292{
293   FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
294
295   /* calloc() implies:
296      memset(br, 0, sizeof(FLAC__BitReader));
297      br->buffer = 0;
298      br->capacity = 0;
299      br->words = br->bytes = 0;
300      br->consumed_words = br->consumed_bits = 0;
301      br->read_callback = 0;
302      br->client_data = 0;
303   */
304   return br;
305}
306
307void FLAC__bitreader_delete(FLAC__BitReader *br)
308{
309   FLAC__ASSERT(0 != br);
310
311   FLAC__bitreader_free(br);
312   free(br);
313}
314
315/***********************************************************************
316 *
317 * Public class methods
318 *
319 ***********************************************************************/
320
321FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
322{
323   FLAC__ASSERT(0 != br);
324
325   br->words = br->bytes = 0;
326   br->consumed_words = br->consumed_bits = 0;
327   br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
328   br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
329   if(br->buffer == 0)
330      return false;
331   br->read_callback = rcb;
332   br->client_data = cd;
333   br->cpu_info = cpu;
334
335   return true;
336}
337
338void FLAC__bitreader_free(FLAC__BitReader *br)
339{
340   FLAC__ASSERT(0 != br);
341
342   if(0 != br->buffer)
343      free(br->buffer);
344   br->buffer = 0;
345   br->capacity = 0;
346   br->words = br->bytes = 0;
347   br->consumed_words = br->consumed_bits = 0;
348   br->read_callback = 0;
349   br->client_data = 0;
350}
351
352FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
353{
354   br->words = br->bytes = 0;
355   br->consumed_words = br->consumed_bits = 0;
356   return true;
357}
358
359void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
360{
361   unsigned i, j;
362   if(br == 0) {
363      fprintf(out, "bitreader is NULL\n");
364   }
365   else {
366      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);
367
368      for(i = 0; i < br->words; i++) {
369         fprintf(out, "%08X: ", i);
370         for(j = 0; j < FLAC__BITS_PER_WORD; j++)
371            if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
372               fprintf(out, ".");
373            else
374               fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
375         fprintf(out, "\n");
376      }
377      if(br->bytes > 0) {
378         fprintf(out, "%08X: ", i);
379         for(j = 0; j < br->bytes*8; j++)
380            if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
381               fprintf(out, ".");
382            else
383               fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
384         fprintf(out, "\n");
385      }
386   }
387}
388
389void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
390{
391   FLAC__ASSERT(0 != br);
392   FLAC__ASSERT(0 != br->buffer);
393   FLAC__ASSERT((br->consumed_bits & 7) == 0);
394
395   br->read_crc16 = (unsigned)seed;
396   br->crc16_align = br->consumed_bits;
397}
398
399FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
400{
401   FLAC__ASSERT(0 != br);
402   FLAC__ASSERT(0 != br->buffer);
403   FLAC__ASSERT((br->consumed_bits & 7) == 0);
404   FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
405
406   /* CRC any tail bytes in a partially-consumed word */
407   if(br->consumed_bits) {
408      const brword tail = br->buffer[br->consumed_words];
409      for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
410         br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
411   }
412   return br->read_crc16;
413}
414
415FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
416{
417   return ((br->consumed_bits & 7) == 0);
418}
419
420FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
421{
422   return 8 - (br->consumed_bits & 7);
423}
424
425FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
426{
427   return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
428}
429
430FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
431{
432   FLAC__ASSERT(0 != br);
433   FLAC__ASSERT(0 != br->buffer);
434
435   FLAC__ASSERT(bits <= 32);
436   FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
437   FLAC__ASSERT(br->consumed_words <= br->words);
438
439   /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
440   FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
441
442   if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
443      *val = 0;
444      return true;
445   }
446
447   while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
448      if(!bitreader_read_from_client_(br))
449         return false;
450   }
451   if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
452      /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
453      if(br->consumed_bits) {
454         /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
455         const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
456         const brword word = br->buffer[br->consumed_words];
457         if(bits < n) {
458            *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
459            br->consumed_bits += bits;
460            return true;
461         }
462         *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
463         bits -= n;
464         crc16_update_word_(br, word);
465         br->consumed_words++;
466         br->consumed_bits = 0;
467         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 */
468            *val <<= bits;
469            *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
470            br->consumed_bits = bits;
471         }
472         return true;
473      }
474      else {
475         const brword word = br->buffer[br->consumed_words];
476         if(bits < FLAC__BITS_PER_WORD) {
477            *val = word >> (FLAC__BITS_PER_WORD-bits);
478            br->consumed_bits = bits;
479            return true;
480         }
481         /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
482         *val = word;
483         crc16_update_word_(br, word);
484         br->consumed_words++;
485         return true;
486      }
487   }
488   else {
489      /* in this case we're starting our read at a partial tail word;
490       * the reader has guaranteed that we have at least 'bits' bits
491       * available to read, which makes this case simpler.
492       */
493      /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
494      if(br->consumed_bits) {
495         /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
496         FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
497         *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
498         br->consumed_bits += bits;
499         return true;
500      }
501      else {
502         *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
503         br->consumed_bits += bits;
504         return true;
505      }
506   }
507}
508
509FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
510{
511   /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
512   if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
513      return false;
514   /* sign-extend: */
515   *val <<= (32-bits);
516   *val >>= (32-bits);
517   return true;
518}
519
520FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
521{
522   FLAC__uint32 hi, lo;
523
524   if(bits > 32) {
525      if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
526         return false;
527      if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
528         return false;
529      *val = hi;
530      *val <<= 32;
531      *val |= lo;
532   }
533   else {
534      if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
535         return false;
536      *val = lo;
537   }
538   return true;
539}
540
541FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
542{
543   FLAC__uint32 x8, x32 = 0;
544
545   /* this doesn't need to be that fast as currently it is only used for vorbis comments */
546
547   if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
548      return false;
549
550   if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
551      return false;
552   x32 |= (x8 << 8);
553
554   if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
555      return false;
556   x32 |= (x8 << 16);
557
558   if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
559      return false;
560   x32 |= (x8 << 24);
561
562   *val = x32;
563   return true;
564}
565
566FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
567{
568   /*
569    * OPT: a faster implementation is possible but probably not that useful
570    * since this is only called a couple of times in the metadata readers.
571    */
572   FLAC__ASSERT(0 != br);
573   FLAC__ASSERT(0 != br->buffer);
574
575   if(bits > 0) {
576      const unsigned n = br->consumed_bits & 7;
577      unsigned m;
578      FLAC__uint32 x;
579
580      if(n != 0) {
581         m = min(8-n, bits);
582         if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
583            return false;
584         bits -= m;
585      }
586      m = bits / 8;
587      if(m > 0) {
588         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
589            return false;
590         bits %= 8;
591      }
592      if(bits > 0) {
593         if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
594            return false;
595      }
596   }
597
598   return true;
599}
600
601FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
602{
603   FLAC__uint32 x;
604
605   FLAC__ASSERT(0 != br);
606   FLAC__ASSERT(0 != br->buffer);
607   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
608
609   /* step 1: skip over partial head word to get word aligned */
610   while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
611      if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
612         return false;
613      nvals--;
614   }
615   if(0 == nvals)
616      return true;
617   /* step 2: skip whole words in chunks */
618   while(nvals >= FLAC__BYTES_PER_WORD) {
619      if(br->consumed_words < br->words) {
620         br->consumed_words++;
621         nvals -= FLAC__BYTES_PER_WORD;
622      }
623      else if(!bitreader_read_from_client_(br))
624         return false;
625   }
626   /* step 3: skip any remainder from partial tail bytes */
627   while(nvals) {
628      if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
629         return false;
630      nvals--;
631   }
632
633   return true;
634}
635
636FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
637{
638   FLAC__uint32 x;
639
640   FLAC__ASSERT(0 != br);
641   FLAC__ASSERT(0 != br->buffer);
642   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
643
644   /* step 1: read from partial head word to get word aligned */
645   while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
646      if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
647         return false;
648      *val++ = (FLAC__byte)x;
649      nvals--;
650   }
651   if(0 == nvals)
652      return true;
653   /* step 2: read whole words in chunks */
654   while(nvals >= FLAC__BYTES_PER_WORD) {
655      if(br->consumed_words < br->words) {
656         const brword word = br->buffer[br->consumed_words++];
657#if FLAC__BYTES_PER_WORD == 4
658         val[0] = (FLAC__byte)(word >> 24);
659         val[1] = (FLAC__byte)(word >> 16);
660         val[2] = (FLAC__byte)(word >> 8);
661         val[3] = (FLAC__byte)word;
662#elif FLAC__BYTES_PER_WORD == 8
663         val[0] = (FLAC__byte)(word >> 56);
664         val[1] = (FLAC__byte)(word >> 48);
665         val[2] = (FLAC__byte)(word >> 40);
666         val[3] = (FLAC__byte)(word >> 32);
667         val[4] = (FLAC__byte)(word >> 24);
668         val[5] = (FLAC__byte)(word >> 16);
669         val[6] = (FLAC__byte)(word >> 8);
670         val[7] = (FLAC__byte)word;
671#else
672         for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
673            val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
674#endif
675         val += FLAC__BYTES_PER_WORD;
676         nvals -= FLAC__BYTES_PER_WORD;
677      }
678      else if(!bitreader_read_from_client_(br))
679         return false;
680   }
681   /* step 3: read any remainder from partial tail bytes */
682   while(nvals) {
683      if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
684         return false;
685      *val++ = (FLAC__byte)x;
686      nvals--;
687   }
688
689   return true;
690}
691
692FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
693#if 0 /* slow but readable version */
694{
695   unsigned bit;
696
697   FLAC__ASSERT(0 != br);
698   FLAC__ASSERT(0 != br->buffer);
699
700   *val = 0;
701   while(1) {
702      if(!FLAC__bitreader_read_bit(br, &bit))
703         return false;
704      if(bit)
705         break;
706      else
707         *val++;
708   }
709   return true;
710}
711#else
712{
713   unsigned i;
714
715   FLAC__ASSERT(0 != br);
716   FLAC__ASSERT(0 != br->buffer);
717
718   *val = 0;
719   while(1) {
720      while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
721         brword b = br->buffer[br->consumed_words] << br->consumed_bits;
722         if(b) {
723            i = COUNT_ZERO_MSBS(b);
724            *val += i;
725            i++;
726            br->consumed_bits += i;
727            if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
728               crc16_update_word_(br, br->buffer[br->consumed_words]);
729               br->consumed_words++;
730               br->consumed_bits = 0;
731            }
732            return true;
733         }
734         else {
735            *val += FLAC__BITS_PER_WORD - br->consumed_bits;
736            crc16_update_word_(br, br->buffer[br->consumed_words]);
737            br->consumed_words++;
738            br->consumed_bits = 0;
739            /* didn't find stop bit yet, have to keep going... */
740         }
741      }
742      /* at this point we've eaten up all the whole words; have to try
743       * reading through any tail bytes before calling the read callback.
744       * this is a repeat of the above logic adjusted for the fact we
745       * don't have a whole word.  note though if the client is feeding
746       * us data a byte at a time (unlikely), br->consumed_bits may not
747       * be zero.
748       */
749      if(br->bytes) {
750         const unsigned end = br->bytes * 8;
751         brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
752         if(b) {
753            i = COUNT_ZERO_MSBS(b);
754            *val += i;
755            i++;
756            br->consumed_bits += i;
757            FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
758            return true;
759         }
760         else {
761            *val += end - br->consumed_bits;
762            br->consumed_bits += end;
763            FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
764            /* didn't find stop bit yet, have to keep going... */
765         }
766      }
767      if(!bitreader_read_from_client_(br))
768         return false;
769   }
770}
771#endif
772
773FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
774{
775   FLAC__uint32 lsbs = 0, msbs = 0;
776   unsigned uval;
777
778   FLAC__ASSERT(0 != br);
779   FLAC__ASSERT(0 != br->buffer);
780   FLAC__ASSERT(parameter <= 31);
781
782   /* read the unary MSBs and end bit */
783   if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
784      return false;
785
786   /* read the binary LSBs */
787   if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
788      return false;
789
790   /* compose the value */
791   uval = (msbs << parameter) | lsbs;
792   if(uval & 1)
793      *val = -((int)(uval >> 1)) - 1;
794   else
795      *val = (int)(uval >> 1);
796
797   return true;
798}
799
800/* this is by far the most heavily used reader call.  it ain't pretty but it's fast */
801/* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
802FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
803/* OPT: possibly faster version for use with MSVC */
804#ifdef _MSC_VER
805{
806   unsigned i;
807   unsigned uval = 0;
808   unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
809
810   /* try and get br->consumed_words and br->consumed_bits into register;
811    * must remember to flush them back to *br before calling other
812    * bitwriter functions that use them, and before returning */
813   register unsigned cwords;
814   register unsigned cbits;
815
816   FLAC__ASSERT(0 != br);
817   FLAC__ASSERT(0 != br->buffer);
818   /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
819   FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
820   FLAC__ASSERT(parameter < 32);
821   /* 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 */
822
823   if(nvals == 0)
824      return true;
825
826   cbits = br->consumed_bits;
827   cwords = br->consumed_words;
828
829   while(1) {
830
831      /* read unary part */
832      while(1) {
833         while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
834            brword b = br->buffer[cwords] << cbits;
835            if(b) {
836#if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
837               __asm {
838                  bsr eax, b
839                  not eax
840                  and eax, 31
841                  mov i, eax
842               }
843#else
844               i = COUNT_ZERO_MSBS(b);
845#endif
846               uval += i;
847               bits = parameter;
848               i++;
849               cbits += i;
850               if(cbits == FLAC__BITS_PER_WORD) {
851                  crc16_update_word_(br, br->buffer[cwords]);
852                  cwords++;
853                  cbits = 0;
854               }
855               goto break1;
856            }
857            else {
858               uval += FLAC__BITS_PER_WORD - cbits;
859               crc16_update_word_(br, br->buffer[cwords]);
860               cwords++;
861               cbits = 0;
862               /* didn't find stop bit yet, have to keep going... */
863            }
864         }
865         /* at this point we've eaten up all the whole words; have to try
866          * reading through any tail bytes before calling the read callback.
867          * this is a repeat of the above logic adjusted for the fact we
868          * don't have a whole word.  note though if the client is feeding
869          * us data a byte at a time (unlikely), br->consumed_bits may not
870          * be zero.
871          */
872         if(br->bytes) {
873            const unsigned end = br->bytes * 8;
874            brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
875            if(b) {
876               i = COUNT_ZERO_MSBS(b);
877               uval += i;
878               bits = parameter;
879               i++;
880               cbits += i;
881               FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
882               goto break1;
883            }
884            else {
885               uval += end - cbits;
886               cbits += end;
887               FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
888               /* didn't find stop bit yet, have to keep going... */
889            }
890         }
891         /* flush registers and read; bitreader_read_from_client_() does
892          * not touch br->consumed_bits at all but we still need to set
893          * it in case it fails and we have to return false.
894          */
895         br->consumed_bits = cbits;
896         br->consumed_words = cwords;
897         if(!bitreader_read_from_client_(br))
898            return false;
899         cwords = br->consumed_words;
900      }
901break1:
902      /* read binary part */
903      FLAC__ASSERT(cwords <= br->words);
904
905      if(bits) {
906         while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
907            /* flush registers and read; bitreader_read_from_client_() does
908             * not touch br->consumed_bits at all but we still need to set
909             * it in case it fails and we have to return false.
910             */
911            br->consumed_bits = cbits;
912            br->consumed_words = cwords;
913            if(!bitreader_read_from_client_(br))
914               return false;
915            cwords = br->consumed_words;
916         }
917         if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
918            if(cbits) {
919               /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
920               const unsigned n = FLAC__BITS_PER_WORD - cbits;
921               const brword word = br->buffer[cwords];
922               if(bits < n) {
923                  uval <<= bits;
924                  uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
925                  cbits += bits;
926                  goto break2;
927               }
928               uval <<= n;
929               uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
930               bits -= n;
931               crc16_update_word_(br, word);
932               cwords++;
933               cbits = 0;
934               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 */
935                  uval <<= bits;
936                  uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
937                  cbits = bits;
938               }
939               goto break2;
940            }
941            else {
942               FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
943               uval <<= bits;
944               uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
945               cbits = bits;
946               goto break2;
947            }
948         }
949         else {
950            /* in this case we're starting our read at a partial tail word;
951             * the reader has guaranteed that we have at least 'bits' bits
952             * available to read, which makes this case simpler.
953             */
954            uval <<= bits;
955            if(cbits) {
956               /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
957               FLAC__ASSERT(cbits + bits <= br->bytes*8);
958               uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
959               cbits += bits;
960               goto break2;
961            }
962            else {
963               uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
964               cbits += bits;
965               goto break2;
966            }
967         }
968      }
969break2:
970      /* compose the value */
971      *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
972
973      /* are we done? */
974      --nvals;
975      if(nvals == 0) {
976         br->consumed_bits = cbits;
977         br->consumed_words = cwords;
978         return true;
979      }
980
981      uval = 0;
982      ++vals;
983
984   }
985}
986#else
987{
988   unsigned i;
989   unsigned uval = 0;
990
991   /* try and get br->consumed_words and br->consumed_bits into register;
992    * must remember to flush them back to *br before calling other
993    * bitwriter functions that use them, and before returning */
994   register unsigned cwords;
995   register unsigned cbits;
996   unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
997
998   FLAC__ASSERT(0 != br);
999   FLAC__ASSERT(0 != br->buffer);
1000   /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
1001   FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
1002   FLAC__ASSERT(parameter < 32);
1003   /* 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 */
1004
1005   if(nvals == 0)
1006      return true;
1007
1008   cbits = br->consumed_bits;
1009   cwords = br->consumed_words;
1010   ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
1011
1012   while(1) {
1013
1014      /* read unary part */
1015      while(1) {
1016         while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
1017            brword b = br->buffer[cwords] << cbits;
1018            if(b) {
1019#if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
1020               asm volatile (
1021                  "bsrl %1, %0;"
1022                  "notl %0;"
1023                  "andl $31, %0;"
1024                  : "=r"(i)
1025                  : "r"(b)
1026               );
1027#else
1028               i = COUNT_ZERO_MSBS(b);
1029#endif
1030               uval += i;
1031               cbits += i;
1032               cbits++; /* skip over stop bit */
1033               if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
1034                  crc16_update_word_(br, br->buffer[cwords]);
1035                  cwords++;
1036                  cbits = 0;
1037               }
1038               goto break1;
1039            }
1040            else {
1041               uval += FLAC__BITS_PER_WORD - cbits;
1042               crc16_update_word_(br, br->buffer[cwords]);
1043               cwords++;
1044               cbits = 0;
1045               /* didn't find stop bit yet, have to keep going... */
1046            }
1047         }
1048         /* at this point we've eaten up all the whole words; have to try
1049          * reading through any tail bytes before calling the read callback.
1050          * this is a repeat of the above logic adjusted for the fact we
1051          * don't have a whole word.  note though if the client is feeding
1052          * us data a byte at a time (unlikely), br->consumed_bits may not
1053          * be zero.
1054          */
1055         if(br->bytes) {
1056            const unsigned end = br->bytes * 8;
1057            brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
1058            if(b) {
1059               i = COUNT_ZERO_MSBS(b);
1060               uval += i;
1061               cbits += i;
1062               cbits++; /* skip over stop bit */
1063               FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
1064               goto break1;
1065            }
1066            else {
1067               uval += end - cbits;
1068               cbits += end;
1069               FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
1070               /* didn't find stop bit yet, have to keep going... */
1071            }
1072         }
1073         /* flush registers and read; bitreader_read_from_client_() does
1074          * not touch br->consumed_bits at all but we still need to set
1075          * it in case it fails and we have to return false.
1076          */
1077         br->consumed_bits = cbits;
1078         br->consumed_words = cwords;
1079         if(!bitreader_read_from_client_(br))
1080            return false;
1081         cwords = br->consumed_words;
1082         ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
1083         /* + uval to offset our count by the # of unary bits already
1084          * consumed before the read, because we will add these back
1085          * in all at once at break1
1086          */
1087      }
1088break1:
1089      ucbits -= uval;
1090      ucbits--; /* account for stop bit */
1091
1092      /* read binary part */
1093      FLAC__ASSERT(cwords <= br->words);
1094
1095      if(parameter) {
1096         while(ucbits < parameter) {
1097            /* flush registers and read; bitreader_read_from_client_() does
1098             * not touch br->consumed_bits at all but we still need to set
1099             * it in case it fails and we have to return false.
1100             */
1101            br->consumed_bits = cbits;
1102            br->consumed_words = cwords;
1103            if(!bitreader_read_from_client_(br))
1104               return false;
1105            cwords = br->consumed_words;
1106            ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
1107         }
1108         if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
1109            if(cbits) {
1110               /* this also works when consumed_bits==0, it's just slower than necessary for that case */
1111               const unsigned n = FLAC__BITS_PER_WORD - cbits;
1112               const brword word = br->buffer[cwords];
1113               if(parameter < n) {
1114                  uval <<= parameter;
1115                  uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
1116                  cbits += parameter;
1117               }
1118               else {
1119                  uval <<= n;
1120                  uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
1121                  crc16_update_word_(br, word);
1122                  cwords++;
1123                  cbits = parameter - n;
1124                  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 */
1125                     uval <<= cbits;
1126                     uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
1127                  }
1128               }
1129            }
1130            else {
1131               cbits = parameter;
1132               uval <<= parameter;
1133               uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
1134            }
1135         }
1136         else {
1137            /* in this case we're starting our read at a partial tail word;
1138             * the reader has guaranteed that we have at least 'parameter'
1139             * bits available to read, which makes this case simpler.
1140             */
1141            uval <<= parameter;
1142            if(cbits) {
1143               /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
1144               FLAC__ASSERT(cbits + parameter <= br->bytes*8);
1145               uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
1146               cbits += parameter;
1147            }
1148            else {
1149               cbits = parameter;
1150               uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
1151            }
1152         }
1153      }
1154
1155      ucbits -= parameter;
1156
1157      /* compose the value */
1158      *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
1159
1160      /* are we done? */
1161      --nvals;
1162      if(nvals == 0) {
1163         br->consumed_bits = cbits;
1164         br->consumed_words = cwords;
1165         return true;
1166      }
1167
1168      uval = 0;
1169      ++vals;
1170
1171   }
1172}
1173#endif
1174
1175#if 0 /* UNUSED */
1176FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
1177{
1178   FLAC__uint32 lsbs = 0, msbs = 0;
1179   unsigned bit, uval, k;
1180
1181   FLAC__ASSERT(0 != br);
1182   FLAC__ASSERT(0 != br->buffer);
1183
1184   k = FLAC__bitmath_ilog2(parameter);
1185
1186   /* read the unary MSBs and end bit */
1187   if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
1188      return false;
1189
1190   /* read the binary LSBs */
1191   if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
1192      return false;
1193
1194   if(parameter == 1u<<k) {
1195      /* compose the value */
1196      uval = (msbs << k) | lsbs;
1197   }
1198   else {
1199      unsigned d = (1 << (k+1)) - parameter;
1200      if(lsbs >= d) {
1201         if(!FLAC__bitreader_read_bit(br, &bit))
1202            return false;
1203         lsbs <<= 1;
1204         lsbs |= bit;
1205         lsbs -= d;
1206      }
1207      /* compose the value */
1208      uval = msbs * parameter + lsbs;
1209   }
1210
1211   /* unfold unsigned to signed */
1212   if(uval & 1)
1213      *val = -((int)(uval >> 1)) - 1;
1214   else
1215      *val = (int)(uval >> 1);
1216
1217   return true;
1218}
1219
1220FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
1221{
1222   FLAC__uint32 lsbs, msbs = 0;
1223   unsigned bit, k;
1224
1225   FLAC__ASSERT(0 != br);
1226   FLAC__ASSERT(0 != br->buffer);
1227
1228   k = FLAC__bitmath_ilog2(parameter);
1229
1230   /* read the unary MSBs and end bit */
1231   if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
1232      return false;
1233
1234   /* read the binary LSBs */
1235   if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
1236      return false;
1237
1238   if(parameter == 1u<<k) {
1239      /* compose the value */
1240      *val = (msbs << k) | lsbs;
1241   }
1242   else {
1243      unsigned d = (1 << (k+1)) - parameter;
1244      if(lsbs >= d) {
1245         if(!FLAC__bitreader_read_bit(br, &bit))
1246            return false;
1247         lsbs <<= 1;
1248         lsbs |= bit;
1249         lsbs -= d;
1250      }
1251      /* compose the value */
1252      *val = msbs * parameter + lsbs;
1253   }
1254
1255   return true;
1256}
1257#endif /* UNUSED */
1258
1259/* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
1260FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
1261{
1262   FLAC__uint32 v = 0;
1263   FLAC__uint32 x;
1264   unsigned i;
1265
1266   if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
1267      return false;
1268   if(raw)
1269      raw[(*rawlen)++] = (FLAC__byte)x;
1270   if(!(x & 0x80)) { /* 0xxxxxxx */
1271      v = x;
1272      i = 0;
1273   }
1274   else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
1275      v = x & 0x1F;
1276      i = 1;
1277   }
1278   else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
1279      v = x & 0x0F;
1280      i = 2;
1281   }
1282   else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
1283      v = x & 0x07;
1284      i = 3;
1285   }
1286   else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
1287      v = x & 0x03;
1288      i = 4;
1289   }
1290   else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
1291      v = x & 0x01;
1292      i = 5;
1293   }
1294   else {
1295      *val = 0xffffffff;
1296      return true;
1297   }
1298   for( ; i; i--) {
1299      if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
1300         return false;
1301      if(raw)
1302         raw[(*rawlen)++] = (FLAC__byte)x;
1303      if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
1304         *val = 0xffffffff;
1305         return true;
1306      }
1307      v <<= 6;
1308      v |= (x & 0x3F);
1309   }
1310   *val = v;
1311   return true;
1312}
1313
1314/* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
1315FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
1316{
1317   FLAC__uint64 v = 0;
1318   FLAC__uint32 x;
1319   unsigned i;
1320
1321   if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
1322      return false;
1323   if(raw)
1324      raw[(*rawlen)++] = (FLAC__byte)x;
1325   if(!(x & 0x80)) { /* 0xxxxxxx */
1326      v = x;
1327      i = 0;
1328   }
1329   else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
1330      v = x & 0x1F;
1331      i = 1;
1332   }
1333   else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
1334      v = x & 0x0F;
1335      i = 2;
1336   }
1337   else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
1338      v = x & 0x07;
1339      i = 3;
1340   }
1341   else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
1342      v = x & 0x03;
1343      i = 4;
1344   }
1345   else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
1346      v = x & 0x01;
1347      i = 5;
1348   }
1349   else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
1350      v = 0;
1351      i = 6;
1352   }
1353   else {
1354      *val = FLAC__U64L(0xffffffffffffffff);
1355      return true;
1356   }
1357   for( ; i; i--) {
1358      if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
1359         return false;
1360      if(raw)
1361         raw[(*rawlen)++] = (FLAC__byte)x;
1362      if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
1363         *val = FLAC__U64L(0xffffffffffffffff);
1364         return true;
1365      }
1366      v <<= 6;
1367      v |= (x & 0x3F);
1368   }
1369   *val = v;
1370   return true;
1371}
src/lib/libflac/libflac/float.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include "flac/assert.h"
37
38#include "private/float.h"
39
40#ifdef FLAC__INTEGER_ONLY_LIBRARY
41
42/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
43#ifdef _MSC_VER
44#define FLAC__U64L(x) x
45#else
46#define FLAC__U64L(x) x##LLU
47#endif
48
49const FLAC__fixedpoint FLAC__FP_ZERO = 0;
50const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
51const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
52const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
53const FLAC__fixedpoint FLAC__FP_E = 178145;
54
55/* Lookup tables for Knuth's logarithm algorithm */
56#define LOG2_LOOKUP_PRECISION 16
57static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
58   {
59      /*
60       * 0 fraction bits
61       */
62      /* undefined */ 0x00000000,
63      /* lg(2/1) = */ 0x00000001,
64      /* lg(4/3) = */ 0x00000000,
65      /* lg(8/7) = */ 0x00000000,
66      /* lg(16/15) = */ 0x00000000,
67      /* lg(32/31) = */ 0x00000000,
68      /* lg(64/63) = */ 0x00000000,
69      /* lg(128/127) = */ 0x00000000,
70      /* lg(256/255) = */ 0x00000000,
71      /* lg(512/511) = */ 0x00000000,
72      /* lg(1024/1023) = */ 0x00000000,
73      /* lg(2048/2047) = */ 0x00000000,
74      /* lg(4096/4095) = */ 0x00000000,
75      /* lg(8192/8191) = */ 0x00000000,
76      /* lg(16384/16383) = */ 0x00000000,
77      /* lg(32768/32767) = */ 0x00000000
78   },
79   {
80      /*
81       * 4 fraction bits
82       */
83      /* undefined */ 0x00000000,
84      /* lg(2/1) = */ 0x00000010,
85      /* lg(4/3) = */ 0x00000007,
86      /* lg(8/7) = */ 0x00000003,
87      /* lg(16/15) = */ 0x00000001,
88      /* lg(32/31) = */ 0x00000001,
89      /* lg(64/63) = */ 0x00000000,
90      /* lg(128/127) = */ 0x00000000,
91      /* lg(256/255) = */ 0x00000000,
92      /* lg(512/511) = */ 0x00000000,
93      /* lg(1024/1023) = */ 0x00000000,
94      /* lg(2048/2047) = */ 0x00000000,
95      /* lg(4096/4095) = */ 0x00000000,
96      /* lg(8192/8191) = */ 0x00000000,
97      /* lg(16384/16383) = */ 0x00000000,
98      /* lg(32768/32767) = */ 0x00000000
99   },
100   {
101      /*
102       * 8 fraction bits
103       */
104      /* undefined */ 0x00000000,
105      /* lg(2/1) = */ 0x00000100,
106      /* lg(4/3) = */ 0x0000006a,
107      /* lg(8/7) = */ 0x00000031,
108      /* lg(16/15) = */ 0x00000018,
109      /* lg(32/31) = */ 0x0000000c,
110      /* lg(64/63) = */ 0x00000006,
111      /* lg(128/127) = */ 0x00000003,
112      /* lg(256/255) = */ 0x00000001,
113      /* lg(512/511) = */ 0x00000001,
114      /* lg(1024/1023) = */ 0x00000000,
115      /* lg(2048/2047) = */ 0x00000000,
116      /* lg(4096/4095) = */ 0x00000000,
117      /* lg(8192/8191) = */ 0x00000000,
118      /* lg(16384/16383) = */ 0x00000000,
119      /* lg(32768/32767) = */ 0x00000000
120   },
121   {
122      /*
123       * 12 fraction bits
124       */
125      /* undefined */ 0x00000000,
126      /* lg(2/1) = */ 0x00001000,
127      /* lg(4/3) = */ 0x000006a4,
128      /* lg(8/7) = */ 0x00000315,
129      /* lg(16/15) = */ 0x0000017d,
130      /* lg(32/31) = */ 0x000000bc,
131      /* lg(64/63) = */ 0x0000005d,
132      /* lg(128/127) = */ 0x0000002e,
133      /* lg(256/255) = */ 0x00000017,
134      /* lg(512/511) = */ 0x0000000c,
135      /* lg(1024/1023) = */ 0x00000006,
136      /* lg(2048/2047) = */ 0x00000003,
137      /* lg(4096/4095) = */ 0x00000001,
138      /* lg(8192/8191) = */ 0x00000001,
139      /* lg(16384/16383) = */ 0x00000000,
140      /* lg(32768/32767) = */ 0x00000000
141   },
142   {
143      /*
144       * 16 fraction bits
145       */
146      /* undefined */ 0x00000000,
147      /* lg(2/1) = */ 0x00010000,
148      /* lg(4/3) = */ 0x00006a40,
149      /* lg(8/7) = */ 0x00003151,
150      /* lg(16/15) = */ 0x000017d6,
151      /* lg(32/31) = */ 0x00000bba,
152      /* lg(64/63) = */ 0x000005d1,
153      /* lg(128/127) = */ 0x000002e6,
154      /* lg(256/255) = */ 0x00000172,
155      /* lg(512/511) = */ 0x000000b9,
156      /* lg(1024/1023) = */ 0x0000005c,
157      /* lg(2048/2047) = */ 0x0000002e,
158      /* lg(4096/4095) = */ 0x00000017,
159      /* lg(8192/8191) = */ 0x0000000c,
160      /* lg(16384/16383) = */ 0x00000006,
161      /* lg(32768/32767) = */ 0x00000003
162   },
163   {
164      /*
165       * 20 fraction bits
166       */
167      /* undefined */ 0x00000000,
168      /* lg(2/1) = */ 0x00100000,
169      /* lg(4/3) = */ 0x0006a3fe,
170      /* lg(8/7) = */ 0x00031513,
171      /* lg(16/15) = */ 0x00017d60,
172      /* lg(32/31) = */ 0x0000bb9d,
173      /* lg(64/63) = */ 0x00005d10,
174      /* lg(128/127) = */ 0x00002e59,
175      /* lg(256/255) = */ 0x00001721,
176      /* lg(512/511) = */ 0x00000b8e,
177      /* lg(1024/1023) = */ 0x000005c6,
178      /* lg(2048/2047) = */ 0x000002e3,
179      /* lg(4096/4095) = */ 0x00000171,
180      /* lg(8192/8191) = */ 0x000000b9,
181      /* lg(16384/16383) = */ 0x0000005c,
182      /* lg(32768/32767) = */ 0x0000002e
183   },
184   {
185      /*
186       * 24 fraction bits
187       */
188      /* undefined */ 0x00000000,
189      /* lg(2/1) = */ 0x01000000,
190      /* lg(4/3) = */ 0x006a3fe6,
191      /* lg(8/7) = */ 0x00315130,
192      /* lg(16/15) = */ 0x0017d605,
193      /* lg(32/31) = */ 0x000bb9ca,
194      /* lg(64/63) = */ 0x0005d0fc,
195      /* lg(128/127) = */ 0x0002e58f,
196      /* lg(256/255) = */ 0x0001720e,
197      /* lg(512/511) = */ 0x0000b8d8,
198      /* lg(1024/1023) = */ 0x00005c61,
199      /* lg(2048/2047) = */ 0x00002e2d,
200      /* lg(4096/4095) = */ 0x00001716,
201      /* lg(8192/8191) = */ 0x00000b8b,
202      /* lg(16384/16383) = */ 0x000005c5,
203      /* lg(32768/32767) = */ 0x000002e3
204   },
205   {
206      /*
207       * 28 fraction bits
208       */
209      /* undefined */ 0x00000000,
210      /* lg(2/1) = */ 0x10000000,
211      /* lg(4/3) = */ 0x06a3fe5c,
212      /* lg(8/7) = */ 0x03151301,
213      /* lg(16/15) = */ 0x017d6049,
214      /* lg(32/31) = */ 0x00bb9ca6,
215      /* lg(64/63) = */ 0x005d0fba,
216      /* lg(128/127) = */ 0x002e58f7,
217      /* lg(256/255) = */ 0x001720da,
218      /* lg(512/511) = */ 0x000b8d87,
219      /* lg(1024/1023) = */ 0x0005c60b,
220      /* lg(2048/2047) = */ 0x0002e2d7,
221      /* lg(4096/4095) = */ 0x00017160,
222      /* lg(8192/8191) = */ 0x0000b8ad,
223      /* lg(16384/16383) = */ 0x00005c56,
224      /* lg(32768/32767) = */ 0x00002e2b
225   }
226};
227
228#if 0
229static const FLAC__uint64 log2_lookup_wide[] = {
230   {
231      /*
232       * 32 fraction bits
233       */
234      /* undefined */ 0x00000000,
235      /* lg(2/1) = */ FLAC__U64L(0x100000000),
236      /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
237      /* lg(8/7) = */ FLAC__U64L(0x31513015),
238      /* lg(16/15) = */ FLAC__U64L(0x17d60497),
239      /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
240      /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
241      /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
242      /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
243      /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
244      /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
245      /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
246      /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
247      /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
248      /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
249      /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
250   },
251   {
252      /*
253       * 48 fraction bits
254       */
255      /* undefined */ 0x00000000,
256      /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
257      /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
258      /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
259      /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
260      /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
261      /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
262      /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
263      /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
264      /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
265      /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
266      /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
267      /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
268      /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
269      /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
270      /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
271   }
272};
273#endif
274
275FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
276{
277   const FLAC__uint32 ONE = (1u << fracbits);
278   const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
279
280   FLAC__ASSERT(fracbits < 32);
281   FLAC__ASSERT((fracbits & 0x3) == 0);
282
283   if(x < ONE)
284      return 0;
285   
286   if(precision > LOG2_LOOKUP_PRECISION)
287      precision = LOG2_LOOKUP_PRECISION;
288
289   /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
290   {
291      FLAC__uint32 y = 0;
292      FLAC__uint32 z = x >> 1, k = 1;
293      while (x > ONE && k < precision) {
294         if (x - z >= ONE) {
295            x -= z;
296            z = x >> k;
297            y += table[k];
298         }
299         else {
300            z >>= 1;
301            k++;
302         }
303      }
304      return y;
305   }
306}
307
308#endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
src/lib/libflac/libflac/metadata_object.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include <stdlib.h>
37#include <string.h>
38
39#include "private/metadata.h"
40
41#include "flac/assert.h"
42#include "share/alloc.h"
43
44
45/****************************************************************************
46 *
47 * Local routines
48 *
49 ***************************************************************************/
50
51/* copy bytes:
52 *  from = NULL  && bytes = 0
53 *       to <- NULL
54 *  from != NULL && bytes > 0
55 *       to <- copy of from
56 *  else ASSERT
57 * malloc error leaves 'to' unchanged
58 */
59static FLAC__bool copy_bytes_(FLAC__byte **to, const FLAC__byte *from, unsigned bytes)
60{
61   FLAC__ASSERT(0 != to);
62   if(bytes > 0 && 0 != from) {
63      FLAC__byte *x;
64      if(0 == (x = (FLAC__byte*)safe_malloc_(bytes)))
65         return false;
66      memcpy(x, from, bytes);
67      *to = x;
68   }
69   else {
70      FLAC__ASSERT(0 == from);
71      FLAC__ASSERT(bytes == 0);
72      *to = 0;
73   }
74   return true;
75}
76
77#if 0 /* UNUSED */
78/* like copy_bytes_(), but free()s the original '*to' if the copy succeeds and the original '*to' is non-NULL */
79static FLAC__bool free_copy_bytes_(FLAC__byte **to, const FLAC__byte *from, unsigned bytes)
80{
81   FLAC__byte *copy;
82   FLAC__ASSERT(0 != to);
83   if(copy_bytes_(&copy, from, bytes)) {
84      if(*to)
85         free(*to);
86      *to = copy;
87      return true;
88   }
89   else
90      return false;
91}
92#endif
93
94/* reallocate entry to 1 byte larger and add a terminating NUL */
95/* realloc() failure leaves entry unchanged */
96static FLAC__bool ensure_null_terminated_(FLAC__byte **entry, unsigned length)
97{
98   FLAC__byte *x = (FLAC__byte*)safe_realloc_add_2op_(*entry, length, /*+*/1);
99   if(0 != x) {
100      x[length] = '\0';
101      *entry = x;
102      return true;
103   }
104   else
105      return false;
106}
107
108/* copies the NUL-terminated C-string 'from' to '*to', leaving '*to'
109 * unchanged if malloc fails, free()ing the original '*to' if it
110 * succeeds and the original '*to' was not NULL
111 */
112static FLAC__bool copy_cstring_(char **to, const char *from)
113{
114   char *copy = strdup(from);
115   FLAC__ASSERT(to);
116   if(copy) {
117      if(*to)
118         free(*to);
119      *to = copy;
120      return true;
121   }
122   else
123      return false;
124}
125
126static FLAC__bool copy_vcentry_(FLAC__StreamMetadata_VorbisComment_Entry *to, const FLAC__StreamMetadata_VorbisComment_Entry *from)
127{
128   to->length = from->length;
129   if(0 == from->entry) {
130      FLAC__ASSERT(from->length == 0);
131      to->entry = 0;
132   }
133   else {
134      FLAC__byte *x;
135      FLAC__ASSERT(from->length > 0);
136      if(0 == (x = (FLAC__byte*)safe_malloc_add_2op_(from->length, /*+*/1)))
137         return false;
138      memcpy(x, from->entry, from->length);
139      x[from->length] = '\0';
140      to->entry = x;
141   }
142   return true;
143}
144
145static FLAC__bool copy_track_(FLAC__StreamMetadata_CueSheet_Track *to, const FLAC__StreamMetadata_CueSheet_Track *from)
146{
147   memcpy(to, from, sizeof(FLAC__StreamMetadata_CueSheet_Track));
148   if(0 == from->indices) {
149      FLAC__ASSERT(from->num_indices == 0);
150   }
151   else {
152      FLAC__StreamMetadata_CueSheet_Index *x;
153      FLAC__ASSERT(from->num_indices > 0);
154      if(0 == (x = (FLAC__StreamMetadata_CueSheet_Index*)safe_malloc_mul_2op_(from->num_indices, /*times*/sizeof(FLAC__StreamMetadata_CueSheet_Index))))
155         return false;
156      memcpy(x, from->indices, from->num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index));
157      to->indices = x;
158   }
159   return true;
160}
161
162static void seektable_calculate_length_(FLAC__StreamMetadata *object)
163{
164   FLAC__ASSERT(0 != object);
165   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
166
167   object->length = object->data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
168}
169
170static FLAC__StreamMetadata_SeekPoint *seekpoint_array_new_(unsigned num_points)
171{
172   FLAC__StreamMetadata_SeekPoint *object_array;
173
174   FLAC__ASSERT(num_points > 0);
175
176   object_array = (FLAC__StreamMetadata_SeekPoint*)safe_malloc_mul_2op_(num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint));
177
178   if(0 != object_array) {
179      unsigned i;
180      for(i = 0; i < num_points; i++) {
181         object_array[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
182         object_array[i].stream_offset = 0;
183         object_array[i].frame_samples = 0;
184      }
185   }
186
187   return object_array;
188}
189
190static void vorbiscomment_calculate_length_(FLAC__StreamMetadata *object)
191{
192   unsigned i;
193
194   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
195
196   object->length = (FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN) / 8;
197   object->length += object->data.vorbis_comment.vendor_string.length;
198   object->length += (FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8;
199   for(i = 0; i < object->data.vorbis_comment.num_comments; i++) {
200      object->length += (FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8);
201      object->length += object->data.vorbis_comment.comments[i].length;
202   }
203}
204
205static FLAC__StreamMetadata_VorbisComment_Entry *vorbiscomment_entry_array_new_(unsigned num_comments)
206{
207   FLAC__ASSERT(num_comments > 0);
208
209   return (FLAC__StreamMetadata_VorbisComment_Entry*)safe_calloc_(num_comments, sizeof(FLAC__StreamMetadata_VorbisComment_Entry));
210}
211
212static void vorbiscomment_entry_array_delete_(FLAC__StreamMetadata_VorbisComment_Entry *object_array, unsigned num_comments)
213{
214   unsigned i;
215
216   FLAC__ASSERT(0 != object_array && num_comments > 0);
217
218   for(i = 0; i < num_comments; i++)
219      if(0 != object_array[i].entry)
220         free(object_array[i].entry);
221
222   if(0 != object_array)
223      free(object_array);
224}
225
226static FLAC__StreamMetadata_VorbisComment_Entry *vorbiscomment_entry_array_copy_(const FLAC__StreamMetadata_VorbisComment_Entry *object_array, unsigned num_comments)
227{
228   FLAC__StreamMetadata_VorbisComment_Entry *return_array;
229
230   FLAC__ASSERT(0 != object_array);
231   FLAC__ASSERT(num_comments > 0);
232
233   return_array = vorbiscomment_entry_array_new_(num_comments);
234
235   if(0 != return_array) {
236      unsigned i;
237
238      for(i = 0; i < num_comments; i++) {
239         if(!copy_vcentry_(return_array+i, object_array+i)) {
240            vorbiscomment_entry_array_delete_(return_array, num_comments);
241            return 0;
242         }
243      }
244   }
245
246   return return_array;
247}
248
249static FLAC__bool vorbiscomment_set_entry_(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry *dest, const FLAC__StreamMetadata_VorbisComment_Entry *src, FLAC__bool copy)
250{
251   FLAC__byte *save;
252
253   FLAC__ASSERT(0 != object);
254   FLAC__ASSERT(0 != dest);
255   FLAC__ASSERT(0 != src);
256   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
257   FLAC__ASSERT((0 != src->entry && src->length > 0) || (0 == src->entry && src->length == 0));
258
259   save = dest->entry;
260
261   if(0 != src->entry && src->length > 0) {
262      if(copy) {
263         /* do the copy first so that if we fail we leave the dest object untouched */
264         if(!copy_vcentry_(dest, src))
265            return false;
266      }
267      else {
268         /* we have to make sure that the string we're taking over is null-terminated */
269
270         /*
271          * Stripping the const from src->entry is OK since we're taking
272          * ownership of the pointer.  This is a hack around a deficiency
273          * in the API where the same function is used for 'copy' and
274          * 'own', but the source entry is a const pointer.  If we were
275          * precise, the 'own' flavor would be a separate function with a
276          * non-const source pointer.  But it's not, so we hack away.
277          */
278         if(!ensure_null_terminated_((FLAC__byte**)(&src->entry), src->length))
279            return false;
280         *dest = *src;
281      }
282   }
283   else {
284      /* the src is null */
285      *dest = *src;
286   }
287
288   if(0 != save)
289      free(save);
290
291   vorbiscomment_calculate_length_(object);
292   return true;
293}
294
295static int vorbiscomment_find_entry_from_(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name, unsigned field_name_length)
296{
297   unsigned i;
298
299   FLAC__ASSERT(0 != object);
300   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
301   FLAC__ASSERT(0 != field_name);
302
303   for(i = offset; i < object->data.vorbis_comment.num_comments; i++) {
304      if(FLAC__metadata_object_vorbiscomment_entry_matches(object->data.vorbis_comment.comments[i], field_name, field_name_length))
305         return (int)i;
306   }
307
308   return -1;
309}
310
311static void cuesheet_calculate_length_(FLAC__StreamMetadata *object)
312{
313   unsigned i;
314
315   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
316
317   object->length = (
318      FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN +
319      FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN +
320      FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN +
321      FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN +
322      FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN
323   ) / 8;
324
325   object->length += object->data.cue_sheet.num_tracks * (
326      FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN +
327      FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN +
328      FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN +
329      FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN +
330      FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN +
331      FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN +
332      FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN
333   ) / 8;
334
335   for(i = 0; i < object->data.cue_sheet.num_tracks; i++) {
336      object->length += object->data.cue_sheet.tracks[i].num_indices * (
337         FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN +
338         FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN +
339         FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN
340      ) / 8;
341   }
342}
343
344static FLAC__StreamMetadata_CueSheet_Index *cuesheet_track_index_array_new_(unsigned num_indices)
345{
346   FLAC__ASSERT(num_indices > 0);
347
348   return (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index));
349}
350
351static FLAC__StreamMetadata_CueSheet_Track *cuesheet_track_array_new_(unsigned num_tracks)
352{
353   FLAC__ASSERT(num_tracks > 0);
354
355   return (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track));
356}
357
358static void cuesheet_track_array_delete_(FLAC__StreamMetadata_CueSheet_Track *object_array, unsigned num_tracks)
359{
360   unsigned i;
361
362   FLAC__ASSERT(0 != object_array && num_tracks > 0);
363
364   for(i = 0; i < num_tracks; i++) {
365      if(0 != object_array[i].indices) {
366         FLAC__ASSERT(object_array[i].num_indices > 0);
367         free(object_array[i].indices);
368      }
369   }
370
371   if(0 != object_array)
372      free(object_array);
373}
374
375static FLAC__StreamMetadata_CueSheet_Track *cuesheet_track_array_copy_(const FLAC__StreamMetadata_CueSheet_Track *object_array, unsigned num_tracks)
376{
377   FLAC__StreamMetadata_CueSheet_Track *return_array;
378
379   FLAC__ASSERT(0 != object_array);
380   FLAC__ASSERT(num_tracks > 0);
381
382   return_array = cuesheet_track_array_new_(num_tracks);
383
384   if(0 != return_array) {
385      unsigned i;
386
387      for(i = 0; i < num_tracks; i++) {
388         if(!copy_track_(return_array+i, object_array+i)) {
389            cuesheet_track_array_delete_(return_array, num_tracks);
390            return 0;
391         }
392      }
393   }
394
395   return return_array;
396}
397
398static FLAC__bool cuesheet_set_track_(FLAC__StreamMetadata *object, FLAC__StreamMetadata_CueSheet_Track *dest, const FLAC__StreamMetadata_CueSheet_Track *src, FLAC__bool copy)
399{
400   FLAC__StreamMetadata_CueSheet_Index *save;
401
402   FLAC__ASSERT(0 != object);
403   FLAC__ASSERT(0 != dest);
404   FLAC__ASSERT(0 != src);
405   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
406   FLAC__ASSERT((0 != src->indices && src->num_indices > 0) || (0 == src->indices && src->num_indices == 0));
407
408   save = dest->indices;
409
410   /* do the copy first so that if we fail we leave the object untouched */
411   if(copy) {
412      if(!copy_track_(dest, src))
413         return false;
414   }
415   else {
416      *dest = *src;
417   }
418
419   if(0 != save)
420      free(save);
421
422   cuesheet_calculate_length_(object);
423   return true;
424}
425
426
427/****************************************************************************
428 *
429 * Metadata object routines
430 *
431 ***************************************************************************/
432
433FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type)
434{
435   FLAC__StreamMetadata *object;
436
437   if(type > FLAC__MAX_METADATA_TYPE_CODE)
438      return 0;
439
440   object = (FLAC__StreamMetadata*)calloc(1, sizeof(FLAC__StreamMetadata));
441   if(0 != object) {
442      object->is_last = false;
443      object->type = type;
444      switch(type) {
445         case FLAC__METADATA_TYPE_STREAMINFO:
446            object->length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
447            break;
448         case FLAC__METADATA_TYPE_PADDING:
449            /* calloc() took care of this for us:
450            object->length = 0;
451            */
452            break;
453         case FLAC__METADATA_TYPE_APPLICATION:
454            object->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
455            /* calloc() took care of this for us:
456            object->data.application.data = 0;
457            */
458            break;
459         case FLAC__METADATA_TYPE_SEEKTABLE:
460            /* calloc() took care of this for us:
461            object->length = 0;
462            object->data.seek_table.num_points = 0;
463            object->data.seek_table.points = 0;
464            */
465            break;
466         case FLAC__METADATA_TYPE_VORBIS_COMMENT:
467            object->data.vorbis_comment.vendor_string.length = (unsigned)strlen(FLAC__VENDOR_STRING);
468            if(!copy_bytes_(&object->data.vorbis_comment.vendor_string.entry, (const FLAC__byte*)FLAC__VENDOR_STRING, object->data.vorbis_comment.vendor_string.length+1)) {
469               free(object);
470               return 0;
471            }
472            vorbiscomment_calculate_length_(object);
473            break;
474         case FLAC__METADATA_TYPE_CUESHEET:
475            cuesheet_calculate_length_(object);
476            break;
477         case FLAC__METADATA_TYPE_PICTURE:
478            object->length = (
479               FLAC__STREAM_METADATA_PICTURE_TYPE_LEN +
480               FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN + /* empty mime_type string */
481               FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN + /* empty description string */
482               FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN +
483               FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN +
484               FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN +
485               FLAC__STREAM_METADATA_PICTURE_COLORS_LEN +
486               FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN +
487               0 /* no data */
488            ) / 8;
489            object->data.picture.type = FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER;
490            object->data.picture.mime_type = 0;
491            object->data.picture.description = 0;
492            /* calloc() took care of this for us:
493            object->data.picture.width = 0;
494            object->data.picture.height = 0;
495            object->data.picture.depth = 0;
496            object->data.picture.colors = 0;
497            object->data.picture.data_length = 0;
498            object->data.picture.data = 0;
499            */
500            /* now initialize mime_type and description with empty strings to make things easier on the client */
501            if(!copy_cstring_(&object->data.picture.mime_type, "")) {
502               free(object);
503               return 0;
504            }
505            if(!copy_cstring_((char**)(&object->data.picture.description), "")) {
506               if(object->data.picture.mime_type)
507                  free(object->data.picture.mime_type);
508               free(object);
509               return 0;
510            }
511            break;
512         default:
513            /* calloc() took care of this for us:
514            object->length = 0;
515            object->data.unknown.data = 0;
516            */
517            break;
518      }
519   }
520
521   return object;
522}
523
524FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object)
525{
526   FLAC__StreamMetadata *to;
527
528   FLAC__ASSERT(0 != object);
529
530   if(0 != (to = FLAC__metadata_object_new(object->type))) {
531      to->is_last = object->is_last;
532      to->type = object->type;
533      to->length = object->length;
534      switch(to->type) {
535         case FLAC__METADATA_TYPE_STREAMINFO:
536            memcpy(&to->data.stream_info, &object->data.stream_info, sizeof(FLAC__StreamMetadata_StreamInfo));
537            break;
538         case FLAC__METADATA_TYPE_PADDING:
539            break;
540         case FLAC__METADATA_TYPE_APPLICATION:
541            if(to->length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8) { /* underflow check */
542               FLAC__metadata_object_delete(to);
543               return 0;
544            }
545            memcpy(&to->data.application.id, &object->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8);
546            if(!copy_bytes_(&to->data.application.data, object->data.application.data, object->length - FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)) {
547               FLAC__metadata_object_delete(to);
548               return 0;
549            }
550            break;
551         case FLAC__METADATA_TYPE_SEEKTABLE:
552            to->data.seek_table.num_points = object->data.seek_table.num_points;
553            if(to->data.seek_table.num_points > SIZE_MAX / sizeof(FLAC__StreamMetadata_SeekPoint)) { /* overflow check */
554               FLAC__metadata_object_delete(to);
555               return 0;
556            }
557            if(!copy_bytes_((FLAC__byte**)&to->data.seek_table.points, (FLAC__byte*)object->data.seek_table.points, object->data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint))) {
558               FLAC__metadata_object_delete(to);
559               return 0;
560            }
561            break;
562         case FLAC__METADATA_TYPE_VORBIS_COMMENT:
563            if(0 != to->data.vorbis_comment.vendor_string.entry) {
564               free(to->data.vorbis_comment.vendor_string.entry);
565               to->data.vorbis_comment.vendor_string.entry = 0;
566            }
567            if(!copy_vcentry_(&to->data.vorbis_comment.vendor_string, &object->data.vorbis_comment.vendor_string)) {
568               FLAC__metadata_object_delete(to);
569               return 0;
570            }
571            if(object->data.vorbis_comment.num_comments == 0) {
572               FLAC__ASSERT(0 == object->data.vorbis_comment.comments);
573               to->data.vorbis_comment.comments = 0;
574            }
575            else {
576               FLAC__ASSERT(0 != object->data.vorbis_comment.comments);
577               to->data.vorbis_comment.comments = vorbiscomment_entry_array_copy_(object->data.vorbis_comment.comments, object->data.vorbis_comment.num_comments);
578               if(0 == to->data.vorbis_comment.comments) {
579                  FLAC__metadata_object_delete(to);
580                  return 0;
581               }
582            }
583            to->data.vorbis_comment.num_comments = object->data.vorbis_comment.num_comments;
584            break;
585         case FLAC__METADATA_TYPE_CUESHEET:
586            memcpy(&to->data.cue_sheet, &object->data.cue_sheet, sizeof(FLAC__StreamMetadata_CueSheet));
587            if(object->data.cue_sheet.num_tracks == 0) {
588               FLAC__ASSERT(0 == object->data.cue_sheet.tracks);
589            }
590            else {
591               FLAC__ASSERT(0 != object->data.cue_sheet.tracks);
592               to->data.cue_sheet.tracks = cuesheet_track_array_copy_(object->data.cue_sheet.tracks, object->data.cue_sheet.num_tracks);
593               if(0 == to->data.cue_sheet.tracks) {
594                  FLAC__metadata_object_delete(to);
595                  return 0;
596               }
597            }
598            break;
599         case FLAC__METADATA_TYPE_PICTURE:
600            to->data.picture.type = object->data.picture.type;
601            if(!copy_cstring_(&to->data.picture.mime_type, object->data.picture.mime_type)) {
602               FLAC__metadata_object_delete(to);
603               return 0;
604            }
605            if(!copy_cstring_((char**)(&to->data.picture.description), (const char*)object->data.picture.description)) {
606               FLAC__metadata_object_delete(to);
607               return 0;
608            }
609            to->data.picture.width = object->data.picture.width;
610            to->data.picture.height = object->data.picture.height;
611            to->data.picture.depth = object->data.picture.depth;
612            to->data.picture.colors = object->data.picture.colors;
613            to->data.picture.data_length = object->data.picture.data_length;
614            if(!copy_bytes_((&to->data.picture.data), object->data.picture.data, object->data.picture.data_length)) {
615               FLAC__metadata_object_delete(to);
616               return 0;
617            }
618            break;
619         default:
620            if(!copy_bytes_(&to->data.unknown.data, object->data.unknown.data, object->length)) {
621               FLAC__metadata_object_delete(to);
622               return 0;
623            }
624            break;
625      }
626   }
627
628   return to;
629}
630
631void FLAC__metadata_object_delete_data(FLAC__StreamMetadata *object)
632{
633   FLAC__ASSERT(0 != object);
634
635   switch(object->type) {
636      case FLAC__METADATA_TYPE_STREAMINFO:
637      case FLAC__METADATA_TYPE_PADDING:
638         break;
639      case FLAC__METADATA_TYPE_APPLICATION:
640         if(0 != object->data.application.data) {
641            free(object->data.application.data);
642            object->data.application.data = 0;
643         }
644         break;
645      case FLAC__METADATA_TYPE_SEEKTABLE:
646         if(0 != object->data.seek_table.points) {
647            free(object->data.seek_table.points);
648            object->data.seek_table.points = 0;
649         }
650         break;
651      case FLAC__METADATA_TYPE_VORBIS_COMMENT:
652         if(0 != object->data.vorbis_comment.vendor_string.entry) {
653            free(object->data.vorbis_comment.vendor_string.entry);
654            object->data.vorbis_comment.vendor_string.entry = 0;
655         }
656         if(0 != object->data.vorbis_comment.comments) {
657            FLAC__ASSERT(object->data.vorbis_comment.num_comments > 0);
658            vorbiscomment_entry_array_delete_(object->data.vorbis_comment.comments, object->data.vorbis_comment.num_comments);
659         }
660         break;
661      case FLAC__METADATA_TYPE_CUESHEET:
662         if(0 != object->data.cue_sheet.tracks) {
663            FLAC__ASSERT(object->data.cue_sheet.num_tracks > 0);
664            cuesheet_track_array_delete_(object->data.cue_sheet.tracks, object->data.cue_sheet.num_tracks);
665         }
666         break;
667      case FLAC__METADATA_TYPE_PICTURE:
668         if(0 != object->data.picture.mime_type) {
669            free(object->data.picture.mime_type);
670            object->data.picture.mime_type = 0;
671         }
672         if(0 != object->data.picture.description) {
673            free(object->data.picture.description);
674            object->data.picture.description = 0;
675         }
676         if(0 != object->data.picture.data) {
677            free(object->data.picture.data);
678            object->data.picture.data = 0;
679         }
680         break;
681      default:
682         if(0 != object->data.unknown.data) {
683            free(object->data.unknown.data);
684            object->data.unknown.data = 0;
685         }
686         break;
687   }
688}
689
690FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object)
691{
692   FLAC__metadata_object_delete_data(object);
693   free(object);
694}
695
696static FLAC__bool compare_block_data_streaminfo_(const FLAC__StreamMetadata_StreamInfo *block1, const FLAC__StreamMetadata_StreamInfo *block2)
697{
698   if(block1->min_blocksize != block2->min_blocksize)
699      return false;
700   if(block1->max_blocksize != block2->max_blocksize)
701      return false;
702   if(block1->min_framesize != block2->min_framesize)
703      return false;
704   if(block1->max_framesize != block2->max_framesize)
705      return false;
706   if(block1->sample_rate != block2->sample_rate)
707      return false;
708   if(block1->channels != block2->channels)
709      return false;
710   if(block1->bits_per_sample != block2->bits_per_sample)
711      return false;
712   if(block1->total_samples != block2->total_samples)
713      return false;
714   if(0 != memcmp(block1->md5sum, block2->md5sum, 16))
715      return false;
716   return true;
717}
718
719static FLAC__bool compare_block_data_application_(const FLAC__StreamMetadata_Application *block1, const FLAC__StreamMetadata_Application *block2, unsigned block_length)
720{
721   FLAC__ASSERT(0 != block1);
722   FLAC__ASSERT(0 != block2);
723   FLAC__ASSERT(block_length >= sizeof(block1->id));
724
725   if(0 != memcmp(block1->id, block2->id, sizeof(block1->id)))
726      return false;
727   if(0 != block1->data && 0 != block2->data)
728      return 0 == memcmp(block1->data, block2->data, block_length - sizeof(block1->id));
729   else
730      return block1->data == block2->data;
731}
732
733static FLAC__bool compare_block_data_seektable_(const FLAC__StreamMetadata_SeekTable *block1, const FLAC__StreamMetadata_SeekTable *block2)
734{
735   unsigned i;
736
737   FLAC__ASSERT(0 != block1);
738   FLAC__ASSERT(0 != block2);
739
740   if(block1->num_points != block2->num_points)
741      return false;
742
743   if(0 != block1->points && 0 != block2->points) {
744      for(i = 0; i < block1->num_points; i++) {
745         if(block1->points[i].sample_number != block2->points[i].sample_number)
746            return false;
747         if(block1->points[i].stream_offset != block2->points[i].stream_offset)
748            return false;
749         if(block1->points[i].frame_samples != block2->points[i].frame_samples)
750            return false;
751      }
752      return true;
753   }
754   else
755      return block1->points == block2->points;
756}
757
758static FLAC__bool compare_block_data_vorbiscomment_(const FLAC__StreamMetadata_VorbisComment *block1, const FLAC__StreamMetadata_VorbisComment *block2)
759{
760   unsigned i;
761
762   if(block1->vendor_string.length != block2->vendor_string.length)
763      return false;
764
765   if(0 != block1->vendor_string.entry && 0 != block2->vendor_string.entry) {
766      if(0 != memcmp(block1->vendor_string.entry, block2->vendor_string.entry, block1->vendor_string.length))
767         return false;
768   }
769   else if(block1->vendor_string.entry != block2->vendor_string.entry)
770      return false;
771
772   if(block1->num_comments != block2->num_comments)
773      return false;
774
775   for(i = 0; i < block1->num_comments; i++) {
776      if(0 != block1->comments[i].entry && 0 != block2->comments[i].entry) {
777         if(0 != memcmp(block1->comments[i].entry, block2->comments[i].entry, block1->comments[i].length))
778            return false;
779      }
780      else if(block1->comments[i].entry != block2->comments[i].entry)
781         return false;
782   }
783   return true;
784}
785
786static FLAC__bool compare_block_data_cuesheet_(const FLAC__StreamMetadata_CueSheet *block1, const FLAC__StreamMetadata_CueSheet *block2)
787{
788   unsigned i, j;
789
790   if(0 != strcmp(block1->media_catalog_number, block2->media_catalog_number))
791      return false;
792
793   if(block1->lead_in != block2->lead_in)
794      return false;
795
796   if(block1->is_cd != block2->is_cd)
797      return false;
798
799   if(block1->num_tracks != block2->num_tracks)
800      return false;
801
802   if(0 != block1->tracks && 0 != block2->tracks) {
803      FLAC__ASSERT(block1->num_tracks > 0);
804      for(i = 0; i < block1->num_tracks; i++) {
805         if(block1->tracks[i].offset != block2->tracks[i].offset)
806            return false;
807         if(block1->tracks[i].number != block2->tracks[i].number)
808            return false;
809         if(0 != memcmp(block1->tracks[i].isrc, block2->tracks[i].isrc, sizeof(block1->tracks[i].isrc)))
810            return false;
811         if(block1->tracks[i].type != block2->tracks[i].type)
812            return false;
813         if(block1->tracks[i].pre_emphasis != block2->tracks[i].pre_emphasis)
814            return false;
815         if(block1->tracks[i].num_indices != block2->tracks[i].num_indices)
816            return false;
817         if(0 != block1->tracks[i].indices && 0 != block2->tracks[i].indices) {
818            FLAC__ASSERT(block1->tracks[i].num_indices > 0);
819            for(j = 0; j < block1->tracks[i].num_indices; j++) {
820               if(block1->tracks[i].indices[j].offset != block2->tracks[i].indices[j].offset)
821                  return false;
822               if(block1->tracks[i].indices[j].number != block2->tracks[i].indices[j].number)
823                  return false;
824            }
825         }
826         else if(block1->tracks[i].indices != block2->tracks[i].indices)
827            return false;
828      }
829   }
830   else if(block1->tracks != block2->tracks)
831      return false;
832   return true;
833}
834
835static FLAC__bool compare_block_data_picture_(const FLAC__StreamMetadata_Picture *block1, const FLAC__StreamMetadata_Picture *block2)
836{
837   if(block1->type != block2->type)
838      return false;
839   if(block1->mime_type != block2->mime_type && (0 == block1->mime_type || 0 == block2->mime_type || strcmp(block1->mime_type, block2->mime_type)))
840      return false;
841   if(block1->description != block2->description && (0 == block1->description || 0 == block2->description || strcmp((const char *)block1->description, (const char *)block2->description)))
842      return false;
843   if(block1->width != block2->width)
844      return false;
845   if(block1->height != block2->height)
846      return false;
847   if(block1->depth != block2->depth)
848      return false;
849   if(block1->colors != block2->colors)
850      return false;
851   if(block1->data_length != block2->data_length)
852      return false;
853   if(block1->data != block2->data && (0 == block1->data || 0 == block2->data || memcmp(block1->data, block2->data, block1->data_length)))
854      return false;
855   return true;
856}
857
858static FLAC__bool compare_block_data_unknown_(const FLAC__StreamMetadata_Unknown *block1, const FLAC__StreamMetadata_Unknown *block2, unsigned block_length)
859{
860   FLAC__ASSERT(0 != block1);
861   FLAC__ASSERT(0 != block2);
862
863   if(0 != block1->data && 0 != block2->data)
864      return 0 == memcmp(block1->data, block2->data, block_length);
865   else
866      return block1->data == block2->data;
867}
868
869FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2)
870{
871   FLAC__ASSERT(0 != block1);
872   FLAC__ASSERT(0 != block2);
873
874   if(block1->type != block2->type) {
875      return false;
876   }
877   if(block1->is_last != block2->is_last) {
878      return false;
879   }
880   if(block1->length != block2->length) {
881      return false;
882   }
883   switch(block1->type) {
884      case FLAC__METADATA_TYPE_STREAMINFO:
885         return compare_block_data_streaminfo_(&block1->data.stream_info, &block2->data.stream_info);
886      case FLAC__METADATA_TYPE_PADDING:
887         return true; /* we don't compare the padding guts */
888      case FLAC__METADATA_TYPE_APPLICATION:
889         return compare_block_data_application_(&block1->data.application, &block2->data.application, block1->length);
890      case FLAC__METADATA_TYPE_SEEKTABLE:
891         return compare_block_data_seektable_(&block1->data.seek_table, &block2->data.seek_table);
892      case FLAC__METADATA_TYPE_VORBIS_COMMENT:
893         return compare_block_data_vorbiscomment_(&block1->data.vorbis_comment, &block2->data.vorbis_comment);
894      case FLAC__METADATA_TYPE_CUESHEET:
895         return compare_block_data_cuesheet_(&block1->data.cue_sheet, &block2->data.cue_sheet);
896      case FLAC__METADATA_TYPE_PICTURE:
897         return compare_block_data_picture_(&block1->data.picture, &block2->data.picture);
898      default:
899         return compare_block_data_unknown_(&block1->data.unknown, &block2->data.unknown, block1->length);
900   }
901}
902
903FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy)
904{
905   FLAC__byte *save;
906
907   FLAC__ASSERT(0 != object);
908   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_APPLICATION);
909   FLAC__ASSERT((0 != data && length > 0) || (0 == data && length == 0 && copy == false));
910
911   save = object->data.application.data;
912
913   /* do the copy first so that if we fail we leave the object untouched */
914   if(copy) {
915      if(!copy_bytes_(&object->data.application.data, data, length))
916         return false;
917   }
918   else {
919      object->data.application.data = data;
920   }
921
922   if(0 != save)
923      free(save);
924
925   object->length = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8 + length;
926   return true;
927}
928
929FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points)
930{
931   FLAC__ASSERT(0 != object);
932   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
933
934   if(0 == object->data.seek_table.points) {
935      FLAC__ASSERT(object->data.seek_table.num_points == 0);
936      if(0 == new_num_points)
937         return true;
938      else if(0 == (object->data.seek_table.points = seekpoint_array_new_(new_num_points)))
939         return false;
940   }
941   else {
942      const size_t old_size = object->data.seek_table.num_points * sizeof(FLAC__StreamMetadata_SeekPoint);
943      const size_t new_size = new_num_points * sizeof(FLAC__StreamMetadata_SeekPoint);
944
945      /* overflow check */
946      if((size_t)new_num_points > SIZE_MAX / sizeof(FLAC__StreamMetadata_SeekPoint))
947         return false;
948
949      FLAC__ASSERT(object->data.seek_table.num_points > 0);
950
951      if(new_size == 0) {
952         free(object->data.seek_table.points);
953         object->data.seek_table.points = 0;
954      }
955      else if(0 == (object->data.seek_table.points = (FLAC__StreamMetadata_SeekPoint*)realloc(object->data.seek_table.points, new_size)))
956         return false;
957
958      /* if growing, set new elements to placeholders */
959      if(new_size > old_size) {
960         unsigned i;
961         for(i = object->data.seek_table.num_points; i < new_num_points; i++) {
962            object->data.seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
963            object->data.seek_table.points[i].stream_offset = 0;
964            object->data.seek_table.points[i].frame_samples = 0;
965         }
966      }
967   }
968
969   object->data.seek_table.num_points = new_num_points;
970
971   seektable_calculate_length_(object);
972   return true;
973}
974
975FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point)
976{
977   FLAC__ASSERT(0 != object);
978   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
979   FLAC__ASSERT(point_num < object->data.seek_table.num_points);
980
981   object->data.seek_table.points[point_num] = point;
982}
983
984FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point)
985{
986   int i;
987
988   FLAC__ASSERT(0 != object);
989   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
990   FLAC__ASSERT(point_num <= object->data.seek_table.num_points);
991
992   if(!FLAC__metadata_object_seektable_resize_points(object, object->data.seek_table.num_points+1))
993      return false;
994
995   /* move all points >= point_num forward one space */
996   for(i = (int)object->data.seek_table.num_points-1; i > (int)point_num; i--)
997      object->data.seek_table.points[i] = object->data.seek_table.points[i-1];
998
999   FLAC__metadata_object_seektable_set_point(object, point_num, point);
1000   seektable_calculate_length_(object);
1001   return true;
1002}
1003
1004FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num)
1005{
1006   unsigned i;
1007
1008   FLAC__ASSERT(0 != object);
1009   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
1010   FLAC__ASSERT(point_num < object->data.seek_table.num_points);
1011
1012   /* move all points > point_num backward one space */
1013   for(i = point_num; i < object->data.seek_table.num_points-1; i++)
1014      object->data.seek_table.points[i] = object->data.seek_table.points[i+1];
1015
1016   return FLAC__metadata_object_seektable_resize_points(object, object->data.seek_table.num_points-1);
1017}
1018
1019FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object)
1020{
1021   FLAC__ASSERT(0 != object);
1022   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
1023
1024   return FLAC__format_seektable_is_legal(&object->data.seek_table);
1025}
1026
1027FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num)
1028{
1029   FLAC__ASSERT(0 != object);
1030   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
1031
1032   if(num > 0)
1033      /* WATCHOUT: we rely on the fact that growing the array adds PLACEHOLDERS at the end */
1034      return FLAC__metadata_object_seektable_resize_points(object, object->data.seek_table.num_points + num);
1035   else
1036      return true;
1037}
1038
1039FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number)
1040{
1041   FLAC__StreamMetadata_SeekTable *seek_table;
1042
1043   FLAC__ASSERT(0 != object);
1044   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
1045
1046   seek_table = &object->data.seek_table;
1047
1048   if(!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + 1))
1049      return false;
1050
1051   seek_table->points[seek_table->num_points - 1].sample_number = sample_number;
1052   seek_table->points[seek_table->num_points - 1].stream_offset = 0;
1053   seek_table->points[seek_table->num_points - 1].frame_samples = 0;
1054
1055   return true;
1056}
1057
1058FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num)
1059{
1060   FLAC__ASSERT(0 != object);
1061   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
1062   FLAC__ASSERT(0 != sample_numbers || num == 0);
1063
1064   if(num > 0) {
1065      FLAC__StreamMetadata_SeekTable *seek_table = &object->data.seek_table;
1066      unsigned i, j;
1067
1068      i = seek_table->num_points;
1069
1070      if(!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + num))
1071         return false;
1072
1073      for(j = 0; j < num; i++, j++) {
1074         seek_table->points[i].sample_number = sample_numbers[j];
1075         seek_table->points[i].stream_offset = 0;
1076         seek_table->points[i].frame_samples = 0;
1077      }
1078   }
1079
1080   return true;
1081}
1082
1083FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples)
1084{
1085   FLAC__ASSERT(0 != object);
1086   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
1087   FLAC__ASSERT(total_samples > 0);
1088
1089   if(num > 0 && total_samples > 0) {
1090      FLAC__StreamMetadata_SeekTable *seek_table = &object->data.seek_table;
1091      unsigned i, j;
1092
1093      i = seek_table->num_points;
1094
1095      if(!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + num))
1096         return false;
1097
1098      for(j = 0; j < num; i++, j++) {
1099         seek_table->points[i].sample_number = total_samples * (FLAC__uint64)j / (FLAC__uint64)num;
1100         seek_table->points[i].stream_offset = 0;
1101         seek_table->points[i].frame_samples = 0;
1102      }
1103   }
1104
1105   return true;
1106}
1107
1108FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples)
1109{
1110   FLAC__ASSERT(0 != object);
1111   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
1112   FLAC__ASSERT(samples > 0);
1113   FLAC__ASSERT(total_samples > 0);
1114
1115   if(samples > 0 && total_samples > 0) {
1116      FLAC__StreamMetadata_SeekTable *seek_table = &object->data.seek_table;
1117      unsigned i, j;
1118      FLAC__uint64 num, sample;
1119
1120      num = 1 + total_samples / samples; /* 1+ for the first sample at 0 */
1121      /* now account for the fact that we don't place a seekpoint at "total_samples" since samples are number from 0: */
1122      if(total_samples % samples == 0)
1123         num--;
1124
1125      i = seek_table->num_points;
1126
1127      if(!FLAC__metadata_object_seektable_resize_points(object, seek_table->num_points + (unsigned)num))
1128         return false;
1129
1130      sample = 0;
1131      for(j = 0; j < num; i++, j++, sample += samples) {
1132         seek_table->points[i].sample_number = sample;
1133         seek_table->points[i].stream_offset = 0;
1134         seek_table->points[i].frame_samples = 0;
1135      }
1136   }
1137
1138   return true;
1139}
1140
1141FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact)
1142{
1143   unsigned unique;
1144
1145   FLAC__ASSERT(0 != object);
1146   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_SEEKTABLE);
1147
1148   unique = FLAC__format_seektable_sort(&object->data.seek_table);
1149
1150   return !compact || FLAC__metadata_object_seektable_resize_points(object, unique);
1151}
1152
1153FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy)
1154{
1155   if(!FLAC__format_vorbiscomment_entry_value_is_legal(entry.entry, entry.length))
1156      return false;
1157   return vorbiscomment_set_entry_(object, &object->data.vorbis_comment.vendor_string, &entry, copy);
1158}
1159
1160FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments)
1161{
1162   FLAC__ASSERT(0 != object);
1163   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1164
1165   if(0 == object->data.vorbis_comment.comments) {
1166      FLAC__ASSERT(object->data.vorbis_comment.num_comments == 0);
1167      if(0 == new_num_comments)
1168         return true;
1169      else if(0 == (object->data.vorbis_comment.comments = vorbiscomment_entry_array_new_(new_num_comments)))
1170         return false;
1171   }
1172   else {
1173      const size_t old_size = object->data.vorbis_comment.num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry);
1174      const size_t new_size = new_num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry);
1175
1176      /* overflow check */
1177      if((size_t)new_num_comments > SIZE_MAX / sizeof(FLAC__StreamMetadata_VorbisComment_Entry))
1178         return false;
1179
1180      FLAC__ASSERT(object->data.vorbis_comment.num_comments > 0);
1181
1182      /* if shrinking, free the truncated entries */
1183      if(new_num_comments < object->data.vorbis_comment.num_comments) {
1184         unsigned i;
1185         for(i = new_num_comments; i < object->data.vorbis_comment.num_comments; i++)
1186            if(0 != object->data.vorbis_comment.comments[i].entry)
1187               free(object->data.vorbis_comment.comments[i].entry);
1188      }
1189
1190      if(new_size == 0) {
1191         free(object->data.vorbis_comment.comments);
1192         object->data.vorbis_comment.comments = 0;
1193      }
1194      else if(0 == (object->data.vorbis_comment.comments = (FLAC__StreamMetadata_VorbisComment_Entry*)realloc(object->data.vorbis_comment.comments, new_size)))
1195         return false;
1196
1197      /* if growing, zero all the length/pointers of new elements */
1198      if(new_size > old_size)
1199         memset(object->data.vorbis_comment.comments + object->data.vorbis_comment.num_comments, 0, new_size - old_size);
1200   }
1201
1202   object->data.vorbis_comment.num_comments = new_num_comments;
1203
1204   vorbiscomment_calculate_length_(object);
1205   return true;
1206}
1207
1208FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy)
1209{
1210   FLAC__ASSERT(0 != object);
1211   FLAC__ASSERT(comment_num < object->data.vorbis_comment.num_comments);
1212
1213   if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length))
1214      return false;
1215   return vorbiscomment_set_entry_(object, &object->data.vorbis_comment.comments[comment_num], &entry, copy);
1216}
1217
1218FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy)
1219{
1220   FLAC__StreamMetadata_VorbisComment *vc;
1221
1222   FLAC__ASSERT(0 != object);
1223   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1224   FLAC__ASSERT(comment_num <= object->data.vorbis_comment.num_comments);
1225
1226   if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length))
1227      return false;
1228
1229   vc = &object->data.vorbis_comment;
1230
1231   if(!FLAC__metadata_object_vorbiscomment_resize_comments(object, vc->num_comments+1))
1232      return false;
1233
1234   /* move all comments >= comment_num forward one space */
1235   memmove(&vc->comments[comment_num+1], &vc->comments[comment_num], sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*(vc->num_comments-1-comment_num));
1236   vc->comments[comment_num].length = 0;
1237   vc->comments[comment_num].entry = 0;
1238
1239   return FLAC__metadata_object_vorbiscomment_set_comment(object, comment_num, entry, copy);
1240}
1241
1242FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy)
1243{
1244   FLAC__ASSERT(0 != object);
1245   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1246   return FLAC__metadata_object_vorbiscomment_insert_comment(object, object->data.vorbis_comment.num_comments, entry, copy);
1247}
1248
1249FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy)
1250{
1251   FLAC__ASSERT(0 != entry.entry && entry.length > 0);
1252
1253   if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length))
1254      return false;
1255
1256   {
1257      int i;
1258      size_t field_name_length;
1259      const FLAC__byte *eq = (FLAC__byte*)memchr(entry.entry, '=', entry.length);
1260
1261      FLAC__ASSERT(0 != eq);
1262
1263      if(0 == eq)
1264         return false; /* double protection */
1265
1266      field_name_length = eq-entry.entry;
1267
1268      if((i = vorbiscomment_find_entry_from_(object, 0, (const char *)entry.entry, field_name_length)) >= 0) {
1269         unsigned index = (unsigned)i;
1270         if(!FLAC__metadata_object_vorbiscomment_set_comment(object, index, entry, copy))
1271            return false;
1272         if(all && (index+1 < object->data.vorbis_comment.num_comments)) {
1273            for(i = vorbiscomment_find_entry_from_(object, index+1, (const char *)entry.entry, field_name_length); i >= 0; ) {
1274               if(!FLAC__metadata_object_vorbiscomment_delete_comment(object, (unsigned)i))
1275                  return false;
1276               if((unsigned)i < object->data.vorbis_comment.num_comments)
1277                  i = vorbiscomment_find_entry_from_(object, (unsigned)i, (const char *)entry.entry, field_name_length);
1278               else
1279                  i = -1;
1280            }
1281         }
1282         return true;
1283      }
1284      else
1285         return FLAC__metadata_object_vorbiscomment_append_comment(object, entry, copy);
1286   }
1287}
1288
1289FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num)
1290{
1291   FLAC__StreamMetadata_VorbisComment *vc;
1292
1293   FLAC__ASSERT(0 != object);
1294   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1295   FLAC__ASSERT(comment_num < object->data.vorbis_comment.num_comments);
1296
1297   vc = &object->data.vorbis_comment;
1298
1299   /* free the comment at comment_num */
1300   if(0 != vc->comments[comment_num].entry)
1301      free(vc->comments[comment_num].entry);
1302
1303   /* move all comments > comment_num backward one space */
1304   memmove(&vc->comments[comment_num], &vc->comments[comment_num+1], sizeof(FLAC__StreamMetadata_VorbisComment_Entry)*(vc->num_comments-comment_num-1));
1305   vc->comments[vc->num_comments-1].length = 0;
1306   vc->comments[vc->num_comments-1].entry = 0;
1307
1308   return FLAC__metadata_object_vorbiscomment_resize_comments(object, vc->num_comments-1);
1309}
1310
1311FLAC_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)
1312{
1313   FLAC__ASSERT(0 != entry);
1314   FLAC__ASSERT(0 != field_name);
1315   FLAC__ASSERT(0 != field_value);
1316
1317   if(!FLAC__format_vorbiscomment_entry_name_is_legal(field_name))
1318      return false;
1319   if(!FLAC__format_vorbiscomment_entry_value_is_legal((const FLAC__byte *)field_value, (unsigned)(-1)))
1320      return false;
1321
1322   {
1323      const size_t nn = strlen(field_name);
1324      const size_t nv = strlen(field_value);
1325      entry->length = nn + 1 /*=*/ + nv;
1326      if(0 == (entry->entry = (FLAC__byte*)safe_malloc_add_4op_(nn, /*+*/1, /*+*/nv, /*+*/1)))
1327         return false;
1328      memcpy(entry->entry, field_name, nn);
1329      entry->entry[nn] = '=';
1330      memcpy(entry->entry+nn+1, field_value, nv);
1331      entry->entry[entry->length] = '\0';
1332   }
1333   
1334   return true;
1335}
1336
1337FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value)
1338{
1339   FLAC__ASSERT(0 != entry.entry && entry.length > 0);
1340   FLAC__ASSERT(0 != field_name);
1341   FLAC__ASSERT(0 != field_value);
1342
1343   if(!FLAC__format_vorbiscomment_entry_is_legal(entry.entry, entry.length))
1344      return false;
1345
1346   {
1347      const FLAC__byte *eq = (FLAC__byte*)memchr(entry.entry, '=', entry.length);
1348      const size_t nn = eq-entry.entry;
1349      const size_t nv = entry.length-nn-1; /* -1 for the '=' */
1350      FLAC__ASSERT(0 != eq);
1351      if(0 == eq)
1352         return false; /* double protection */
1353      if(0 == (*field_name = (char*)safe_malloc_add_2op_(nn, /*+*/1)))
1354         return false;
1355      if(0 == (*field_value = (char*)safe_malloc_add_2op_(nv, /*+*/1))) {
1356         free(*field_name);
1357         return false;
1358      }
1359      memcpy(*field_name, entry.entry, nn);
1360      memcpy(*field_value, entry.entry+nn+1, nv);
1361      (*field_name)[nn] = '\0';
1362      (*field_value)[nv] = '\0';
1363   }
1364
1365   return true;
1366}
1367
1368FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length)
1369{
1370   FLAC__ASSERT(0 != entry.entry && entry.length > 0);
1371   {
1372      const FLAC__byte *eq = (FLAC__byte*)memchr(entry.entry, '=', entry.length);
1373#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ || defined __EMX__
1374#define FLAC__STRNCASECMP strnicmp
1375#else
1376#define FLAC__STRNCASECMP strncasecmp
1377#endif
1378      return (0 != eq && (unsigned)(eq-entry.entry) == field_name_length && 0 == FLAC__STRNCASECMP(field_name, (const char *)entry.entry, field_name_length));
1379#undef FLAC__STRNCASECMP
1380   }
1381}
1382
1383FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name)
1384{
1385   FLAC__ASSERT(0 != field_name);
1386
1387   return vorbiscomment_find_entry_from_(object, offset, field_name, strlen(field_name));
1388}
1389
1390FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name)
1391{
1392   const unsigned field_name_length = strlen(field_name);
1393   unsigned i;
1394
1395   FLAC__ASSERT(0 != object);
1396   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1397
1398   for(i = 0; i < object->data.vorbis_comment.num_comments; i++) {
1399      if(FLAC__metadata_object_vorbiscomment_entry_matches(object->data.vorbis_comment.comments[i], field_name, field_name_length)) {
1400         if(!FLAC__metadata_object_vorbiscomment_delete_comment(object, i))
1401            return -1;
1402         else
1403            return 1;
1404      }
1405   }
1406
1407   return 0;
1408}
1409
1410FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name)
1411{
1412   FLAC__bool ok = true;
1413   unsigned matching = 0;
1414   const unsigned field_name_length = strlen(field_name);
1415   int i;
1416
1417   FLAC__ASSERT(0 != object);
1418   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1419
1420   /* must delete from end to start otherwise it will interfere with our iteration */
1421   for(i = (int)object->data.vorbis_comment.num_comments - 1; ok && i >= 0; i--) {
1422      if(FLAC__metadata_object_vorbiscomment_entry_matches(object->data.vorbis_comment.comments[i], field_name, field_name_length)) {
1423         matching++;
1424         ok &= FLAC__metadata_object_vorbiscomment_delete_comment(object, (unsigned)i);
1425      }
1426   }
1427
1428   return ok? (int)matching : -1;
1429}
1430
1431FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void)
1432{
1433   return (FLAC__StreamMetadata_CueSheet_Track*)calloc(1, sizeof(FLAC__StreamMetadata_CueSheet_Track));
1434}
1435
1436FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object)
1437{
1438   FLAC__StreamMetadata_CueSheet_Track *to;
1439
1440   FLAC__ASSERT(0 != object);
1441
1442   if(0 != (to = FLAC__metadata_object_cuesheet_track_new())) {
1443      if(!copy_track_(to, object)) {
1444         FLAC__metadata_object_cuesheet_track_delete(to);
1445         return 0;
1446      }
1447   }
1448
1449   return to;
1450}
1451
1452void FLAC__metadata_object_cuesheet_track_delete_data(FLAC__StreamMetadata_CueSheet_Track *object)
1453{
1454   FLAC__ASSERT(0 != object);
1455
1456   if(0 != object->indices) {
1457      FLAC__ASSERT(object->num_indices > 0);
1458      free(object->indices);
1459   }
1460}
1461
1462FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object)
1463{
1464   FLAC__metadata_object_cuesheet_track_delete_data(object);
1465   free(object);
1466}
1467
1468FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices)
1469{
1470   FLAC__StreamMetadata_CueSheet_Track *track;
1471   FLAC__ASSERT(0 != object);
1472   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
1473   FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
1474
1475   track = &object->data.cue_sheet.tracks[track_num];
1476
1477   if(0 == track->indices) {
1478      FLAC__ASSERT(track->num_indices == 0);
1479      if(0 == new_num_indices)
1480         return true;
1481      else if(0 == (track->indices = cuesheet_track_index_array_new_(new_num_indices)))
1482         return false;
1483   }
1484   else {
1485      const size_t old_size = track->num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index);
1486      const size_t new_size = new_num_indices * sizeof(FLAC__StreamMetadata_CueSheet_Index);
1487
1488      /* overflow check */
1489      if((size_t)new_num_indices > SIZE_MAX / sizeof(FLAC__StreamMetadata_CueSheet_Index))
1490         return false;
1491
1492      FLAC__ASSERT(track->num_indices > 0);
1493
1494      if(new_size == 0) {
1495         free(track->indices);
1496         track->indices = 0;
1497      }
1498      else if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)realloc(track->indices, new_size)))
1499         return false;
1500
1501      /* if growing, zero all the lengths/pointers of new elements */
1502      if(new_size > old_size)
1503         memset(track->indices + track->num_indices, 0, new_size - old_size);
1504   }
1505
1506   track->num_indices = new_num_indices;
1507
1508   cuesheet_calculate_length_(object);
1509   return true;
1510}
1511
1512FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index)
1513{
1514   FLAC__StreamMetadata_CueSheet_Track *track;
1515
1516   FLAC__ASSERT(0 != object);
1517   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
1518   FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
1519   FLAC__ASSERT(index_num <= object->data.cue_sheet.tracks[track_num].num_indices);
1520
1521   track = &object->data.cue_sheet.tracks[track_num];
1522
1523   if(!FLAC__metadata_object_cuesheet_track_resize_indices(object, track_num, track->num_indices+1))
1524      return false;
1525
1526   /* move all indices >= index_num forward one space */
1527   memmove(&track->indices[index_num+1], &track->indices[index_num], sizeof(FLAC__StreamMetadata_CueSheet_Index)*(track->num_indices-1-index_num));
1528
1529   track->indices[index_num] = index;
1530   cuesheet_calculate_length_(object);
1531   return true;
1532}
1533
1534FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num)
1535{
1536   FLAC__StreamMetadata_CueSheet_Index index;
1537   memset(&index, 0, sizeof(index));
1538   return FLAC__metadata_object_cuesheet_track_insert_index(object, track_num, index_num, index);
1539}
1540
1541FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num)
1542{
1543   FLAC__StreamMetadata_CueSheet_Track *track;
1544
1545   FLAC__ASSERT(0 != object);
1546   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
1547   FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
1548   FLAC__ASSERT(index_num < object->data.cue_sheet.tracks[track_num].num_indices);
1549
1550   track = &object->data.cue_sheet.tracks[track_num];
1551
1552   /* move all indices > index_num backward one space */
1553   memmove(&track->indices[index_num], &track->indices[index_num+1], sizeof(FLAC__StreamMetadata_CueSheet_Index)*(track->num_indices-index_num-1));
1554
1555   FLAC__metadata_object_cuesheet_track_resize_indices(object, track_num, track->num_indices-1);
1556   cuesheet_calculate_length_(object);
1557   return true;
1558}
1559
1560FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks)
1561{
1562   FLAC__ASSERT(0 != object);
1563   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
1564
1565   if(0 == object->data.cue_sheet.tracks) {
1566      FLAC__ASSERT(object->data.cue_sheet.num_tracks == 0);
1567      if(0 == new_num_tracks)
1568         return true;
1569      else if(0 == (object->data.cue_sheet.tracks = cuesheet_track_array_new_(new_num_tracks)))
1570         return false;
1571   }
1572   else {
1573      const size_t old_size = object->data.cue_sheet.num_tracks * sizeof(FLAC__StreamMetadata_CueSheet_Track);
1574      const size_t new_size = new_num_tracks * sizeof(FLAC__StreamMetadata_CueSheet_Track);
1575
1576      /* overflow check */
1577      if((size_t)new_num_tracks > SIZE_MAX / sizeof(FLAC__StreamMetadata_CueSheet_Track))
1578         return false;
1579
1580      FLAC__ASSERT(object->data.cue_sheet.num_tracks > 0);
1581
1582      /* if shrinking, free the truncated entries */
1583      if(new_num_tracks < object->data.cue_sheet.num_tracks) {
1584         unsigned i;
1585         for(i = new_num_tracks; i < object->data.cue_sheet.num_tracks; i++)
1586            if(0 != object->data.cue_sheet.tracks[i].indices)
1587               free(object->data.cue_sheet.tracks[i].indices);
1588      }
1589
1590      if(new_size == 0) {
1591         free(object->data.cue_sheet.tracks);
1592         object->data.cue_sheet.tracks = 0;
1593      }
1594      else if(0 == (object->data.cue_sheet.tracks = (FLAC__StreamMetadata_CueSheet_Track*)realloc(object->data.cue_sheet.tracks, new_size)))
1595         return false;
1596
1597      /* if growing, zero all the lengths/pointers of new elements */
1598      if(new_size > old_size)
1599         memset(object->data.cue_sheet.tracks + object->data.cue_sheet.num_tracks, 0, new_size - old_size);
1600   }
1601
1602   object->data.cue_sheet.num_tracks = new_num_tracks;
1603
1604   cuesheet_calculate_length_(object);
1605   return true;
1606}
1607
1608FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy)
1609{
1610   FLAC__ASSERT(0 != object);
1611   FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
1612
1613   return cuesheet_set_track_(object, object->data.cue_sheet.tracks + track_num, track, copy);
1614}
1615
1616FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy)
1617{
1618   FLAC__StreamMetadata_CueSheet *cs;
1619
1620   FLAC__ASSERT(0 != object);
1621   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
1622   FLAC__ASSERT(track_num <= object->data.cue_sheet.num_tracks);
1623
1624   cs = &object->data.cue_sheet;
1625
1626   if(!FLAC__metadata_object_cuesheet_resize_tracks(object, cs->num_tracks+1))
1627      return false;
1628
1629   /* move all tracks >= track_num forward one space */
1630   memmove(&cs->tracks[track_num+1], &cs->tracks[track_num], sizeof(FLAC__StreamMetadata_CueSheet_Track)*(cs->num_tracks-1-track_num));
1631   cs->tracks[track_num].num_indices = 0;
1632   cs->tracks[track_num].indices = 0;
1633
1634   return FLAC__metadata_object_cuesheet_set_track(object, track_num, track, copy);
1635}
1636
1637FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num)
1638{
1639   FLAC__StreamMetadata_CueSheet_Track track;
1640   memset(&track, 0, sizeof(track));
1641   return FLAC__metadata_object_cuesheet_insert_track(object, track_num, &track, /*copy=*/false);
1642}
1643
1644FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num)
1645{
1646   FLAC__StreamMetadata_CueSheet *cs;
1647
1648   FLAC__ASSERT(0 != object);
1649   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
1650   FLAC__ASSERT(track_num < object->data.cue_sheet.num_tracks);
1651
1652   cs = &object->data.cue_sheet;
1653
1654   /* free the track at track_num */
1655   if(0 != cs->tracks[track_num].indices)
1656      free(cs->tracks[track_num].indices);
1657
1658   /* move all tracks > track_num backward one space */
1659   memmove(&cs->tracks[track_num], &cs->tracks[track_num+1], sizeof(FLAC__StreamMetadata_CueSheet_Track)*(cs->num_tracks-track_num-1));
1660   cs->tracks[cs->num_tracks-1].num_indices = 0;
1661   cs->tracks[cs->num_tracks-1].indices = 0;
1662
1663   return FLAC__metadata_object_cuesheet_resize_tracks(object, cs->num_tracks-1);
1664}
1665
1666FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation)
1667{
1668   FLAC__ASSERT(0 != object);
1669   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
1670
1671   return FLAC__format_cuesheet_is_legal(&object->data.cue_sheet, check_cd_da_subset, violation);
1672}
1673
1674static FLAC__uint64 get_index_01_offset_(const FLAC__StreamMetadata_CueSheet *cs, unsigned track)
1675{
1676   if (track >= (cs->num_tracks-1) || cs->tracks[track].num_indices < 1)
1677      return 0;
1678   else if (cs->tracks[track].indices[0].number == 1)
1679      return cs->tracks[track].indices[0].offset + cs->tracks[track].offset + cs->lead_in;
1680   else if (cs->tracks[track].num_indices < 2)
1681      return 0;
1682   else if (cs->tracks[track].indices[1].number == 1)
1683      return cs->tracks[track].indices[1].offset + cs->tracks[track].offset + cs->lead_in;
1684   else
1685      return 0;
1686}
1687
1688static FLAC__uint32 cddb_add_digits_(FLAC__uint32 x)
1689{
1690   FLAC__uint32 n = 0;
1691   while (x) {
1692      n += (x%10);
1693      x /= 10;
1694   }
1695   return n;
1696}
1697
1698/*@@@@add to tests*/
1699FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object)
1700{
1701   const FLAC__StreamMetadata_CueSheet *cs;
1702
1703   FLAC__ASSERT(0 != object);
1704   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_CUESHEET);
1705
1706   cs = &object->data.cue_sheet;
1707
1708   if (cs->num_tracks < 2) /* need at least one real track and the lead-out track */
1709      return 0;
1710
1711   {
1712      FLAC__uint32 i, length, sum = 0;
1713      for (i = 0; i < (cs->num_tracks-1); i++) /* -1 to avoid counting the lead-out */
1714         sum += cddb_add_digits_((FLAC__uint32)(get_index_01_offset_(cs, i) / 44100));
1715      length = (FLAC__uint32)((cs->tracks[cs->num_tracks-1].offset+cs->lead_in) / 44100) - (FLAC__uint32)(get_index_01_offset_(cs, 0) / 44100);
1716
1717      return (sum % 0xFF) << 24 | length << 8 | (FLAC__uint32)(cs->num_tracks-1);
1718   }
1719}
1720
1721FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy)
1722{
1723   char *old;
1724   size_t old_length, new_length;
1725
1726   FLAC__ASSERT(0 != object);
1727   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE);
1728   FLAC__ASSERT(0 != mime_type);
1729
1730   old = object->data.picture.mime_type;
1731   old_length = old? strlen(old) : 0;
1732   new_length = strlen(mime_type);
1733
1734   /* do the copy first so that if we fail we leave the object untouched */
1735   if(copy) {
1736      if(new_length >= SIZE_MAX) /* overflow check */
1737         return false;
1738      if(!copy_bytes_((FLAC__byte**)(&object->data.picture.mime_type), (FLAC__byte*)mime_type, new_length+1))
1739         return false;
1740   }
1741   else {
1742      object->data.picture.mime_type = mime_type;
1743   }
1744
1745   if(0 != old)
1746      free(old);
1747
1748   object->length -= old_length;
1749   object->length += new_length;
1750   return true;
1751}
1752
1753FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy)
1754{
1755   FLAC__byte *old;
1756   size_t old_length, new_length;
1757
1758   FLAC__ASSERT(0 != object);
1759   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE);
1760   FLAC__ASSERT(0 != description);
1761
1762   old = object->data.picture.description;
1763   old_length = old? strlen((const char *)old) : 0;
1764   new_length = strlen((const char *)description);
1765
1766   /* do the copy first so that if we fail we leave the object untouched */
1767   if(copy) {
1768      if(new_length >= SIZE_MAX) /* overflow check */
1769         return false;
1770      if(!copy_bytes_(&object->data.picture.description, description, new_length+1))
1771         return false;
1772   }
1773   else {
1774      object->data.picture.description = description;
1775   }
1776
1777   if(0 != old)
1778      free(old);
1779
1780   object->length -= old_length;
1781   object->length += new_length;
1782   return true;
1783}
1784
1785FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy)
1786{
1787   FLAC__byte *old;
1788
1789   FLAC__ASSERT(0 != object);
1790   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE);
1791   FLAC__ASSERT((0 != data && length > 0) || (0 == data && length == 0 && copy == false));
1792
1793   old = object->data.picture.data;
1794
1795   /* do the copy first so that if we fail we leave the object untouched */
1796   if(copy) {
1797      if(!copy_bytes_(&object->data.picture.data, data, length))
1798         return false;
1799   }
1800   else {
1801      object->data.picture.data = data;
1802   }
1803
1804   if(0 != old)
1805      free(old);
1806
1807   object->length -= object->data.picture.data_length;
1808   object->data.picture.data_length = length;
1809   object->length += length;
1810   return true;
1811}
1812
1813FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation)
1814{
1815   FLAC__ASSERT(0 != object);
1816   FLAC__ASSERT(object->type == FLAC__METADATA_TYPE_PICTURE);
1817
1818   return FLAC__format_picture_is_legal(&object->data.picture, violation);
1819}
src/lib/libflac/libflac/window.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include <math.h>
37#include "flac/assert.h"
38#include "flac/format.h"
39#include "private/window.h"
40
41#ifndef FLAC__INTEGER_ONLY_LIBRARY
42
43#ifndef M_PI
44/* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
45#define M_PI 3.14159265358979323846
46#endif
47
48
49void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
50{
51   const FLAC__int32 N = L - 1;
52   FLAC__int32 n;
53
54   if (L & 1) {
55      for (n = 0; n <= N/2; n++)
56         window[n] = 2.0f * n / (float)N;
57      for (; n <= N; n++)
58         window[n] = 2.0f - 2.0f * n / (float)N;
59   }
60   else {
61      for (n = 0; n <= L/2-1; n++)
62         window[n] = 2.0f * n / (float)N;
63      for (; n <= N; n++)
64         window[n] = 2.0f - 2.0f * (N-n) / (float)N;
65   }
66}
67
68void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
69{
70   const FLAC__int32 N = L - 1;
71   FLAC__int32 n;
72
73   for (n = 0; n < L; n++)
74      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)));
75}
76
77void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
78{
79   const FLAC__int32 N = L - 1;
80   FLAC__int32 n;
81
82   for (n = 0; n < L; n++)
83      window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
84}
85
86/* 4-term -92dB side-lobe */
87void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
88{
89   const FLAC__int32 N = L - 1;
90   FLAC__int32 n;
91
92   for (n = 0; n <= N; n++)
93      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));
94}
95
96void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
97{
98   const FLAC__int32 N = L - 1;
99   const double N2 = (double)N / 2.;
100   FLAC__int32 n;
101
102   for (n = 0; n <= N; n++) {
103      double k = ((double)n - N2) / N2;
104      k = 1.0f - k * k;
105      window[n] = (FLAC__real)(k * k);
106   }
107}
108
109void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
110{
111   const FLAC__int32 N = L - 1;
112   FLAC__int32 n;
113
114   for (n = 0; n < L; n++)
115      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));
116}
117
118void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
119{
120   const FLAC__int32 N = L - 1;
121   const double N2 = (double)N / 2.;
122   FLAC__int32 n;
123
124   for (n = 0; n <= N; n++) {
125      const double k = ((double)n - N2) / (stddev * N2);
126      window[n] = (FLAC__real)exp(-0.5f * k * k);
127   }
128}
129
130void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
131{
132   const FLAC__int32 N = L - 1;
133   FLAC__int32 n;
134
135   for (n = 0; n < L; n++)
136      window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
137}
138
139void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
140{
141   const FLAC__int32 N = L - 1;
142   FLAC__int32 n;
143
144   for (n = 0; n < L; n++)
145      window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
146}
147
148void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
149{
150   const FLAC__int32 N = L - 1;
151   FLAC__int32 n;
152
153   for (n = 0; n < L; n++)
154      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));
155}
156
157void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
158{
159   const FLAC__int32 N = L - 1;
160   FLAC__int32 n;
161
162   for (n = 0; n < L; n++)
163      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));
164}
165
166void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
167{
168   FLAC__int32 n;
169
170   for (n = 0; n < L; n++)
171      window[n] = 1.0f;
172}
173
174void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
175{
176   FLAC__int32 n;
177
178   if (L & 1) {
179      for (n = 1; n <= L+1/2; n++)
180         window[n-1] = 2.0f * n / ((float)L + 1.0f);
181      for (; n <= L; n++)
182         window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
183   }
184   else {
185      for (n = 1; n <= L/2; n++)
186         window[n-1] = 2.0f * n / (float)L;
187      for (; n <= L; n++)
188         window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
189   }
190}
191
192void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
193{
194   if (p <= 0.0)
195      FLAC__window_rectangle(window, L);
196   else if (p >= 1.0)
197      FLAC__window_hann(window, L);
198   else {
199      const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
200      FLAC__int32 n;
201      /* start with rectangle... */
202      FLAC__window_rectangle(window, L);
203      /* ...replace ends with hann */
204      if (Np > 0) {
205         for (n = 0; n <= Np; n++) {
206            window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
207            window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
208         }
209      }
210   }
211}
212
213void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
214{
215   const FLAC__int32 N = L - 1;
216   const double N2 = (double)N / 2.;
217   FLAC__int32 n;
218
219   for (n = 0; n <= N; n++) {
220      const double k = ((double)n - N2) / N2;
221      window[n] = (FLAC__real)(1.0f - k * k);
222   }
223}
224
225#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
src/lib/libflac/libflac/crc.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include "private/crc.h"
37
38/* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
39
40FLAC__byte const FLAC__crc8_table[256] = {
41   0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
42   0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
43   0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
44   0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
45   0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
46   0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
47   0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
48   0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
49   0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
50   0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
51   0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
52   0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
53   0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
54   0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
55   0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
56   0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
57   0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
58   0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
59   0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
60   0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
61   0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
62   0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
63   0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
64   0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
65   0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
66   0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
67   0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
68   0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
69   0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
70   0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
71   0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
72   0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
73};
74
75/* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
76
77unsigned FLAC__crc16_table[256] = {
78   0x0000,  0x8005,  0x800f,  0x000a,  0x801b,  0x001e,  0x0014,  0x8011,
79   0x8033,  0x0036,  0x003c,  0x8039,  0x0028,  0x802d,  0x8027,  0x0022,
80   0x8063,  0x0066,  0x006c,  0x8069,  0x0078,  0x807d,  0x8077,  0x0072,
81   0x0050,  0x8055,  0x805f,  0x005a,  0x804b,  0x004e,  0x0044,  0x8041,
82   0x80c3,  0x00c6,  0x00cc,  0x80c9,  0x00d8,  0x80dd,  0x80d7,  0x00d2,
83   0x00f0,  0x80f5,  0x80ff,  0x00fa,  0x80eb,  0x00ee,  0x00e4,  0x80e1,
84   0x00a0,  0x80a5,  0x80af,  0x00aa,  0x80bb,  0x00be,  0x00b4,  0x80b1,
85   0x8093,  0x0096,  0x009c,  0x8099,  0x0088,  0x808d,  0x8087,  0x0082,
86   0x8183,  0x0186,  0x018c,  0x8189,  0x0198,  0x819d,  0x8197,  0x0192,
87   0x01b0,  0x81b5,  0x81bf,  0x01ba,  0x81ab,  0x01ae,  0x01a4,  0x81a1,
88   0x01e0,  0x81e5,  0x81ef,  0x01ea,  0x81fb,  0x01fe,  0x01f4,  0x81f1,
89   0x81d3,  0x01d6,  0x01dc,  0x81d9,  0x01c8,  0x81cd,  0x81c7,  0x01c2,
90   0x0140,  0x8145,  0x814f,  0x014a,  0x815b,  0x015e,  0x0154,  0x8151,
91   0x8173,  0x0176,  0x017c,  0x8179,  0x0168,  0x816d,  0x8167,  0x0162,
92   0x8123,  0x0126,  0x012c,  0x8129,  0x0138,  0x813d,  0x8137,  0x0132,
93   0x0110,  0x8115,  0x811f,  0x011a,  0x810b,  0x010e,  0x0104,  0x8101,
94   0x8303,  0x0306,  0x030c,  0x8309,  0x0318,  0x831d,  0x8317,  0x0312,
95   0x0330,  0x8335,  0x833f,  0x033a,  0x832b,  0x032e,  0x0324,  0x8321,
96   0x0360,  0x8365,  0x836f,  0x036a,  0x837b,  0x037e,  0x0374,  0x8371,
97   0x8353,  0x0356,  0x035c,  0x8359,  0x0348,  0x834d,  0x8347,  0x0342,
98   0x03c0,  0x83c5,  0x83cf,  0x03ca,  0x83db,  0x03de,  0x03d4,  0x83d1,
99   0x83f3,  0x03f6,  0x03fc,  0x83f9,  0x03e8,  0x83ed,  0x83e7,  0x03e2,
100   0x83a3,  0x03a6,  0x03ac,  0x83a9,  0x03b8,  0x83bd,  0x83b7,  0x03b2,
101   0x0390,  0x8395,  0x839f,  0x039a,  0x838b,  0x038e,  0x0384,  0x8381,
102   0x0280,  0x8285,  0x828f,  0x028a,  0x829b,  0x029e,  0x0294,  0x8291,
103   0x82b3,  0x02b6,  0x02bc,  0x82b9,  0x02a8,  0x82ad,  0x82a7,  0x02a2,
104   0x82e3,  0x02e6,  0x02ec,  0x82e9,  0x02f8,  0x82fd,  0x82f7,  0x02f2,
105   0x02d0,  0x82d5,  0x82df,  0x02da,  0x82cb,  0x02ce,  0x02c4,  0x82c1,
106   0x8243,  0x0246,  0x024c,  0x8249,  0x0258,  0x825d,  0x8257,  0x0252,
107   0x0270,  0x8275,  0x827f,  0x027a,  0x826b,  0x026e,  0x0264,  0x8261,
108   0x0220,  0x8225,  0x822f,  0x022a,  0x823b,  0x023e,  0x0234,  0x8231,
109   0x8213,  0x0216,  0x021c,  0x8219,  0x0208,  0x820d,  0x8207,  0x0202
110};
111
112
113void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
114{
115   *crc = FLAC__crc8_table[*crc ^ data];
116}
117
118void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
119{
120   while(len--)
121      *crc = FLAC__crc8_table[*crc ^ *data++];
122}
123
124FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
125{
126   FLAC__uint8 crc = 0;
127
128   while(len--)
129      crc = FLAC__crc8_table[crc ^ *data++];
130
131   return crc;
132}
133
134unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
135{
136   unsigned crc = 0;
137
138   while(len--)
139      crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
140
141   return crc;
142}
src/lib/libflac/libflac/memory.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include "private/memory.h"
37#include "flac/assert.h"
38#include "share/alloc.h"
39
40void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
41{
42   void *x;
43
44   FLAC__ASSERT(0 != aligned_address);
45
46#ifdef FLAC__ALIGN_MALLOC_DATA
47   /* align on 32-byte (256-bit) boundary */
48   x = safe_malloc_add_2op_(bytes, /*+*/31);
49#ifdef SIZEOF_VOIDP
50#if SIZEOF_VOIDP == 4
51      /* could do  *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
52      *aligned_address = (void*)(((unsigned)x + 31) & -32);
53#elif SIZEOF_VOIDP == 8
54      *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
55#else
56# error  Unsupported sizeof(void*)
57#endif
58#else
59   /* there's got to be a better way to do this right for all archs */
60   if(sizeof(void*) == sizeof(unsigned))
61      *aligned_address = (void*)(((unsigned)x + 31) & -32);
62   else if(sizeof(void*) == sizeof(FLAC__uint64))
63      *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
64   else
65      return 0;
66#endif
67#else
68   x = safe_malloc_(bytes);
69   *aligned_address = x;
70#endif
71   return x;
72}
73
74FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
75{
76   FLAC__int32 *pu; /* unaligned pointer */
77   union { /* union needed to comply with C99 pointer aliasing rules */
78      FLAC__int32 *pa; /* aligned pointer */
79      void        *pv; /* aligned pointer alias */
80   } u;
81
82   FLAC__ASSERT(elements > 0);
83   FLAC__ASSERT(0 != unaligned_pointer);
84   FLAC__ASSERT(0 != aligned_pointer);
85   FLAC__ASSERT(unaligned_pointer != aligned_pointer);
86
87   if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
88      return false;
89
90   pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
91   if(0 == pu) {
92      return false;
93   }
94   else {
95      if(*unaligned_pointer != 0)
96         free(*unaligned_pointer);
97      *unaligned_pointer = pu;
98      *aligned_pointer = u.pa;
99      return true;
100   }
101}
102
103FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
104{
105   FLAC__uint32 *pu; /* unaligned pointer */
106   union { /* union needed to comply with C99 pointer aliasing rules */
107      FLAC__uint32 *pa; /* aligned pointer */
108      void         *pv; /* aligned pointer alias */
109   } u;
110
111   FLAC__ASSERT(elements > 0);
112   FLAC__ASSERT(0 != unaligned_pointer);
113   FLAC__ASSERT(0 != aligned_pointer);
114   FLAC__ASSERT(unaligned_pointer != aligned_pointer);
115
116   if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
117      return false;
118
119   pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
120   if(0 == pu) {
121      return false;
122   }
123   else {
124      if(*unaligned_pointer != 0)
125         free(*unaligned_pointer);
126      *unaligned_pointer = pu;
127      *aligned_pointer = u.pa;
128      return true;
129   }
130}
131
132FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
133{
134   FLAC__uint64 *pu; /* unaligned pointer */
135   union { /* union needed to comply with C99 pointer aliasing rules */
136      FLAC__uint64 *pa; /* aligned pointer */
137      void         *pv; /* aligned pointer alias */
138   } u;
139
140   FLAC__ASSERT(elements > 0);
141   FLAC__ASSERT(0 != unaligned_pointer);
142   FLAC__ASSERT(0 != aligned_pointer);
143   FLAC__ASSERT(unaligned_pointer != aligned_pointer);
144
145   if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
146      return false;
147
148   pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
149   if(0 == pu) {
150      return false;
151   }
152   else {
153      if(*unaligned_pointer != 0)
154         free(*unaligned_pointer);
155      *unaligned_pointer = pu;
156      *aligned_pointer = u.pa;
157      return true;
158   }
159}
160
161FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
162{
163   unsigned *pu; /* unaligned pointer */
164   union { /* union needed to comply with C99 pointer aliasing rules */
165      unsigned *pa; /* aligned pointer */
166      void     *pv; /* aligned pointer alias */
167   } u;
168
169   FLAC__ASSERT(elements > 0);
170   FLAC__ASSERT(0 != unaligned_pointer);
171   FLAC__ASSERT(0 != aligned_pointer);
172   FLAC__ASSERT(unaligned_pointer != aligned_pointer);
173
174   if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
175      return false;
176
177   pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
178   if(0 == pu) {
179      return false;
180   }
181   else {
182      if(*unaligned_pointer != 0)
183         free(*unaligned_pointer);
184      *unaligned_pointer = pu;
185      *aligned_pointer = u.pa;
186      return true;
187   }
188}
189
190#ifndef FLAC__INTEGER_ONLY_LIBRARY
191
192FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
193{
194   FLAC__real *pu; /* unaligned pointer */
195   union { /* union needed to comply with C99 pointer aliasing rules */
196      FLAC__real *pa; /* aligned pointer */
197      void       *pv; /* aligned pointer alias */
198   } u;
199
200   FLAC__ASSERT(elements > 0);
201   FLAC__ASSERT(0 != unaligned_pointer);
202   FLAC__ASSERT(0 != aligned_pointer);
203   FLAC__ASSERT(unaligned_pointer != aligned_pointer);
204
205   if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
206      return false;
207
208   pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
209   if(0 == pu) {
210      return false;
211   }
212   else {
213      if(*unaligned_pointer != 0)
214         free(*unaligned_pointer);
215      *unaligned_pointer = pu;
216      *aligned_pointer = u.pa;
217      return true;
218   }
219}
220
221#endif
src/lib/libflac/libflac/bitwriter.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36
37
38#include <stdlib.h> /* for malloc() */
39#include <string.h> /* for memcpy(), memset() */
40
41#if 0 /* UNUSED */
42#include "private/bitmath.h"
43#endif
44#include "private/bitwriter.h"
45#include "private/crc.h"
46#include "flac/assert.h"
47#include "share/alloc.h"
48
49/* Things should be fastest when this matches the machine word size */
50/* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
51/* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
52typedef FLAC__uint32 bwword;
53#define FLAC__BYTES_PER_WORD 4
54#define FLAC__BITS_PER_WORD 32
55#define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
56/* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
57#if WORDS_BIGENDIAN
58#define SWAP_BE_WORD_TO_HOST(x) (x)
59#else
60#ifdef _MSC_VER
61#define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
62#else
63#define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
64#endif
65#endif
66
67/*
68 * The default capacity here doesn't matter too much.  The buffer always grows
69 * to hold whatever is written to it.  Usually the encoder will stop adding at
70 * a frame or metadata block, then write that out and clear the buffer for the
71 * next one.
72 */
73static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
74/* When growing, increment 4K at a time */
75static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
76
77#define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
78#define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
79
80#ifdef min
81#undef min
82#endif
83#define min(x,y) ((x)<(y)?(x):(y))
84
85/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
86#ifdef _MSC_VER
87#define FLAC__U64L(x) x
88#else
89#define FLAC__U64L(x) x##LLU
90#endif
91
92#ifndef FLaC__INLINE
93#define FLaC__INLINE
94#endif
95
96struct FLAC__BitWriter {
97   bwword *buffer;
98   bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
99   unsigned capacity; /* capacity of buffer in words */
100   unsigned words; /* # of complete words in buffer */
101   unsigned bits; /* # of used bits in accum */
102};
103
104
105/* OPT: an MSVC built-in would be better */
106static FLAC__uint32 local_swap32_(FLAC__uint32 x)
107{
108   x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
109   return (x>>16) | (x<<16);
110}
111
112
113/* * WATCHOUT: The current implementation only grows the buffer. */
114static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
115{
116   unsigned new_capacity;
117   bwword *new_buffer;
118
119   FLAC__ASSERT(0 != bw);
120   FLAC__ASSERT(0 != bw->buffer);
121
122   /* calculate total words needed to store 'bits_to_add' additional bits */
123   new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
124
125   /* it's possible (due to pessimism in the growth estimation that
126    * leads to this call) that we don't actually need to grow
127    */
128   if(bw->capacity >= new_capacity)
129      return true;
130
131   /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
132   if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
133      new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
134   /* make sure we got everything right */
135   FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
136   FLAC__ASSERT(new_capacity > bw->capacity);
137   FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
138
139   new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
140   if(new_buffer == 0)
141      return false;
142   bw->buffer = new_buffer;
143   bw->capacity = new_capacity;
144   return true;
145}
146
147
148/***********************************************************************
149 *
150 * Class constructor/destructor
151 *
152 ***********************************************************************/
153
154FLAC__BitWriter *FLAC__bitwriter_new(void)
155{
156   FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
157   /* note that calloc() sets all members to 0 for us */
158   return bw;
159}
160
161void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
162{
163   FLAC__ASSERT(0 != bw);
164
165   FLAC__bitwriter_free(bw);
166   free(bw);
167}
168
169/***********************************************************************
170 *
171 * Public class methods
172 *
173 ***********************************************************************/
174
175FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
176{
177   FLAC__ASSERT(0 != bw);
178
179   bw->words = bw->bits = 0;
180   bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
181   bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
182   if(bw->buffer == 0)
183      return false;
184
185   return true;
186}
187
188void FLAC__bitwriter_free(FLAC__BitWriter *bw)
189{
190   FLAC__ASSERT(0 != bw);
191
192   if(0 != bw->buffer)
193      free(bw->buffer);
194   bw->buffer = 0;
195   bw->capacity = 0;
196   bw->words = bw->bits = 0;
197}
198
199void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
200{
201   bw->words = bw->bits = 0;
202}
203
204void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
205{
206   unsigned i, j;
207   if(bw == 0) {
208      fprintf(out, "bitwriter is NULL\n");
209   }
210   else {
211      fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
212
213      for(i = 0; i < bw->words; i++) {
214         fprintf(out, "%08X: ", i);
215         for(j = 0; j < FLAC__BITS_PER_WORD; j++)
216            fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
217         fprintf(out, "\n");
218      }
219      if(bw->bits > 0) {
220         fprintf(out, "%08X: ", i);
221         for(j = 0; j < bw->bits; j++)
222            fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
223         fprintf(out, "\n");
224      }
225   }
226}
227
228FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
229{
230   const FLAC__byte *buffer;
231   size_t bytes;
232
233   FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
234
235   if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
236      return false;
237
238   *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
239   FLAC__bitwriter_release_buffer(bw);
240   return true;
241}
242
243FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
244{
245   const FLAC__byte *buffer;
246   size_t bytes;
247
248   FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
249
250   if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
251      return false;
252
253   *crc = FLAC__crc8(buffer, bytes);
254   FLAC__bitwriter_release_buffer(bw);
255   return true;
256}
257
258FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
259{
260   return ((bw->bits & 7) == 0);
261}
262
263unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
264{
265   return FLAC__TOTAL_BITS(bw);
266}
267
268FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
269{
270   FLAC__ASSERT((bw->bits & 7) == 0);
271   /* double protection */
272   if(bw->bits & 7)
273      return false;
274   /* if we have bits in the accumulator we have to flush those to the buffer first */
275   if(bw->bits) {
276      FLAC__ASSERT(bw->words <= bw->capacity);
277      if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
278         return false;
279      /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
280      bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
281   }
282   /* now we can just return what we have */
283   *buffer = (FLAC__byte*)bw->buffer;
284   *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
285   return true;
286}
287
288void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
289{
290   /* nothing to do.  in the future, strict checking of a 'writer-is-in-
291    * get-mode' flag could be added everywhere and then cleared here
292    */
293   (void)bw;
294}
295
296FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
297{
298   unsigned n;
299
300   FLAC__ASSERT(0 != bw);
301   FLAC__ASSERT(0 != bw->buffer);
302
303   if(bits == 0)
304      return true;
305   /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
306   if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
307      return false;
308   /* first part gets to word alignment */
309   if(bw->bits) {
310      n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
311      bw->accum <<= n;
312      bits -= n;
313      bw->bits += n;
314      if(bw->bits == FLAC__BITS_PER_WORD) {
315         bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
316         bw->bits = 0;
317      }
318      else
319         return true;
320   }
321   /* do whole words */
322   while(bits >= FLAC__BITS_PER_WORD) {
323      bw->buffer[bw->words++] = 0;
324      bits -= FLAC__BITS_PER_WORD;
325   }
326   /* do any leftovers */
327   if(bits > 0) {
328      bw->accum = 0;
329      bw->bits = bits;
330   }
331   return true;
332}
333
334FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
335{
336   register unsigned left;
337
338   /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
339   FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
340
341   FLAC__ASSERT(0 != bw);
342   FLAC__ASSERT(0 != bw->buffer);
343
344   FLAC__ASSERT(bits <= 32);
345   if(bits == 0)
346      return true;
347
348   /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
349   if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
350      return false;
351
352   left = FLAC__BITS_PER_WORD - bw->bits;
353   if(bits < left) {
354      bw->accum <<= bits;
355      bw->accum |= val;
356      bw->bits += bits;
357   }
358   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 */
359      bw->accum <<= left;
360      bw->accum |= val >> (bw->bits = bits - left);
361      bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
362      bw->accum = val;
363   }
364   else {
365      bw->accum = val;
366      bw->bits = 0;
367      bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
368   }
369
370   return true;
371}
372
373FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
374{
375   /* zero-out unused bits */
376   if(bits < 32)
377      val &= (~(0xffffffff << bits));
378
379   return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
380}
381
382FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
383{
384   /* this could be a little faster but it's not used for much */
385   if(bits > 32) {
386      return
387         FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
388         FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
389   }
390   else
391      return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
392}
393
394FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
395{
396   /* this doesn't need to be that fast as currently it is only used for vorbis comments */
397
398   if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
399      return false;
400   if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
401      return false;
402   if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
403      return false;
404   if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
405      return false;
406
407   return true;
408}
409
410FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
411{
412   unsigned i;
413
414   /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
415   for(i = 0; i < nvals; i++) {
416      if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
417         return false;
418   }
419
420   return true;
421}
422
423FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
424{
425   if(val < 32)
426      return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
427   else
428      return
429         FLAC__bitwriter_write_zeroes(bw, val) &&
430         FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
431}
432
433unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
434{
435   FLAC__uint32 uval;
436
437   FLAC__ASSERT(parameter < sizeof(unsigned)*8);
438
439   /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
440   uval = (val<<1) ^ (val>>31);
441
442   return 1 + parameter + (uval >> parameter);
443}
444
445#if 0 /* UNUSED */
446unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
447{
448   unsigned bits, msbs, uval;
449   unsigned k;
450
451   FLAC__ASSERT(parameter > 0);
452
453   /* fold signed to unsigned */
454   if(val < 0)
455      uval = (unsigned)(((-(++val)) << 1) + 1);
456   else
457      uval = (unsigned)(val << 1);
458
459   k = FLAC__bitmath_ilog2(parameter);
460   if(parameter == 1u<<k) {
461      FLAC__ASSERT(k <= 30);
462
463      msbs = uval >> k;
464      bits = 1 + k + msbs;
465   }
466   else {
467      unsigned q, r, d;
468
469      d = (1 << (k+1)) - parameter;
470      q = uval / parameter;
471      r = uval - (q * parameter);
472
473      bits = 1 + q + k;
474      if(r >= d)
475         bits++;
476   }
477   return bits;
478}
479
480unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
481{
482   unsigned bits, msbs;
483   unsigned k;
484
485   FLAC__ASSERT(parameter > 0);
486
487   k = FLAC__bitmath_ilog2(parameter);
488   if(parameter == 1u<<k) {
489      FLAC__ASSERT(k <= 30);
490
491      msbs = uval >> k;
492      bits = 1 + k + msbs;
493   }
494   else {
495      unsigned q, r, d;
496
497      d = (1 << (k+1)) - parameter;
498      q = uval / parameter;
499      r = uval - (q * parameter);
500
501      bits = 1 + q + k;
502      if(r >= d)
503         bits++;
504   }
505   return bits;
506}
507#endif /* UNUSED */
508
509FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
510{
511   unsigned total_bits, interesting_bits, msbs;
512   FLAC__uint32 uval, pattern;
513
514   FLAC__ASSERT(0 != bw);
515   FLAC__ASSERT(0 != bw->buffer);
516   FLAC__ASSERT(parameter < 8*sizeof(uval));
517
518   /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
519   uval = (val<<1) ^ (val>>31);
520
521   msbs = uval >> parameter;
522   interesting_bits = 1 + parameter;
523   total_bits = interesting_bits + msbs;
524   pattern = 1 << parameter; /* the unary end bit */
525   pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
526
527   if(total_bits <= 32)
528      return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
529   else
530      return
531         FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
532         FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
533}
534
535FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
536{
537   const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
538   const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
539   FLAC__uint32 uval;
540   unsigned left;
541   const unsigned lsbits = 1 + parameter;
542   unsigned msbits;
543
544   FLAC__ASSERT(0 != bw);
545   FLAC__ASSERT(0 != bw->buffer);
546   FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
547   /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
548   FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
549
550   while(nvals) {
551      /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
552      uval = (*vals<<1) ^ (*vals>>31);
553
554      msbits = uval >> parameter;
555
556#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) */
557      if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
558         /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
559         bw->bits = bw->bits + msbits + lsbits;
560         uval |= mask1; /* set stop bit */
561         uval &= mask2; /* mask off unused top bits */
562         /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
563         bw->accum <<= msbits;
564         bw->accum <<= lsbits;
565         bw->accum |= uval;
566         if(bw->bits == FLAC__BITS_PER_WORD) {
567            bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
568            bw->bits = 0;
569            /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
570            if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
571               FLAC__ASSERT(bw->capacity == bw->words);
572               return false;
573            }
574         }
575      }
576      else {
577#elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
578      if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
579         /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
580         bw->bits = bw->bits + msbits + lsbits;
581         uval |= mask1; /* set stop bit */
582         uval &= mask2; /* mask off unused top bits */
583         bw->accum <<= msbits + lsbits;
584         bw->accum |= uval;
585      }
586      else {
587#endif
588         /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
589         /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
590         if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
591            return false;
592
593         if(msbits) {
594            /* first part gets to word alignment */
595            if(bw->bits) {
596               left = FLAC__BITS_PER_WORD - bw->bits;
597               if(msbits < left) {
598                  bw->accum <<= msbits;
599                  bw->bits += msbits;
600                  goto break1;
601               }
602               else {
603                  bw->accum <<= left;
604                  msbits -= left;
605                  bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
606                  bw->bits = 0;
607               }
608            }
609            /* do whole words */
610            while(msbits >= FLAC__BITS_PER_WORD) {
611               bw->buffer[bw->words++] = 0;
612               msbits -= FLAC__BITS_PER_WORD;
613            }
614            /* do any leftovers */
615            if(msbits > 0) {
616               bw->accum = 0;
617               bw->bits = msbits;
618            }
619         }
620break1:
621         uval |= mask1; /* set stop bit */
622         uval &= mask2; /* mask off unused top bits */
623
624         left = FLAC__BITS_PER_WORD - bw->bits;
625         if(lsbits < left) {
626            bw->accum <<= lsbits;
627            bw->accum |= uval;
628            bw->bits += lsbits;
629         }
630         else {
631            /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
632             * be > lsbits (because of previous assertions) so it would have
633             * triggered the (lsbits<left) case above.
634             */
635            FLAC__ASSERT(bw->bits);
636            FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
637            bw->accum <<= left;
638            bw->accum |= uval >> (bw->bits = lsbits - left);
639            bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
640            bw->accum = uval;
641         }
642#if 1
643      }
644#endif
645      vals++;
646      nvals--;
647   }
648   return true;
649}
650
651#if 0 /* UNUSED */
652FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
653{
654   unsigned total_bits, msbs, uval;
655   unsigned k;
656
657   FLAC__ASSERT(0 != bw);
658   FLAC__ASSERT(0 != bw->buffer);
659   FLAC__ASSERT(parameter > 0);
660
661   /* fold signed to unsigned */
662   if(val < 0)
663      uval = (unsigned)(((-(++val)) << 1) + 1);
664   else
665      uval = (unsigned)(val << 1);
666
667   k = FLAC__bitmath_ilog2(parameter);
668   if(parameter == 1u<<k) {
669      unsigned pattern;
670
671      FLAC__ASSERT(k <= 30);
672
673      msbs = uval >> k;
674      total_bits = 1 + k + msbs;
675      pattern = 1 << k; /* the unary end bit */
676      pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
677
678      if(total_bits <= 32) {
679         if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
680            return false;
681      }
682      else {
683         /* write the unary MSBs */
684         if(!FLAC__bitwriter_write_zeroes(bw, msbs))
685            return false;
686         /* write the unary end bit and binary LSBs */
687         if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
688            return false;
689      }
690   }
691   else {
692      unsigned q, r, d;
693
694      d = (1 << (k+1)) - parameter;
695      q = uval / parameter;
696      r = uval - (q * parameter);
697      /* write the unary MSBs */
698      if(!FLAC__bitwriter_write_zeroes(bw, q))
699         return false;
700      /* write the unary end bit */
701      if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
702         return false;
703      /* write the binary LSBs */
704      if(r >= d) {
705         if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
706            return false;
707      }
708      else {
709         if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
710            return false;
711      }
712   }
713   return true;
714}
715
716FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
717{
718   unsigned total_bits, msbs;
719   unsigned k;
720
721   FLAC__ASSERT(0 != bw);
722   FLAC__ASSERT(0 != bw->buffer);
723   FLAC__ASSERT(parameter > 0);
724
725   k = FLAC__bitmath_ilog2(parameter);
726   if(parameter == 1u<<k) {
727      unsigned pattern;
728
729      FLAC__ASSERT(k <= 30);
730
731      msbs = uval >> k;
732      total_bits = 1 + k + msbs;
733      pattern = 1 << k; /* the unary end bit */
734      pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
735
736      if(total_bits <= 32) {
737         if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
738            return false;
739      }
740      else {
741         /* write the unary MSBs */
742         if(!FLAC__bitwriter_write_zeroes(bw, msbs))
743            return false;
744         /* write the unary end bit and binary LSBs */
745         if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
746            return false;
747      }
748   }
749   else {
750      unsigned q, r, d;
751
752      d = (1 << (k+1)) - parameter;
753      q = uval / parameter;
754      r = uval - (q * parameter);
755      /* write the unary MSBs */
756      if(!FLAC__bitwriter_write_zeroes(bw, q))
757         return false;
758      /* write the unary end bit */
759      if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
760         return false;
761      /* write the binary LSBs */
762      if(r >= d) {
763         if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
764            return false;
765      }
766      else {
767         if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
768            return false;
769      }
770   }
771   return true;
772}
773#endif /* UNUSED */
774
775FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
776{
777   FLAC__bool ok = 1;
778
779   FLAC__ASSERT(0 != bw);
780   FLAC__ASSERT(0 != bw->buffer);
781
782   FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
783
784   if(val < 0x80) {
785      return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
786   }
787   else if(val < 0x800) {
788      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
789      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
790   }
791   else if(val < 0x10000) {
792      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
793      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
794      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
795   }
796   else if(val < 0x200000) {
797      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
798      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
799      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
800      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
801   }
802   else if(val < 0x4000000) {
803      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
804      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
805      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
806      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
807      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
808   }
809   else {
810      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
811      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
812      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
813      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
814      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
815      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
816   }
817
818   return ok;
819}
820
821FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
822{
823   FLAC__bool ok = 1;
824
825   FLAC__ASSERT(0 != bw);
826   FLAC__ASSERT(0 != bw->buffer);
827
828   FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
829
830   if(val < 0x80) {
831      return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
832   }
833   else if(val < 0x800) {
834      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
835      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
836   }
837   else if(val < 0x10000) {
838      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
839      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
840      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
841   }
842   else if(val < 0x200000) {
843      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
844      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
845      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
846      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
847   }
848   else if(val < 0x4000000) {
849      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
850      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
851      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
852      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
853      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
854   }
855   else if(val < 0x80000000) {
856      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
857      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
858      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
859      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
860      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
861      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
862   }
863   else {
864      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
865      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
866      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
867      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
868      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
869      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
870      ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
871   }
872
873   return ok;
874}
875
876FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
877{
878   /* 0-pad to byte boundary */
879   if(bw->bits & 7u)
880      return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
881   else
882      return true;
883}
src/lib/libflac/libflac/metadata_iterators.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include <errno.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40
41#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
42#if defined __BORLANDC__
43#include <utime.h> /* for utime() */
44#else
45#include <sys/utime.h> /* for utime() */
46#endif
47#include <io.h> /* for chmod() */
48#include <sys/types.h> /* for off_t */
49#if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
50#define fseeko fseek
51#define ftello ftell
52#endif
53#else
54#include <sys/types.h> /* some flavors of BSD (like OS X) require this to get time_t */
55#include <utime.h> /* for utime() */
56#include <unistd.h> /* for chown(), unlink() */
57#endif
58#include <sys/stat.h> /* for stat(), maybe chmod() */
59
60#include "private/metadata.h"
61
62#include "flac/assert.h"
63#include "flac/stream_decoder.h"
64#include "share/alloc.h"
65
66#ifdef max
67#undef max
68#endif
69#define max(a,b) ((a)>(b)?(a):(b))
70#ifdef min
71#undef min
72#endif
73#define min(a,b) ((a)<(b)?(a):(b))
74
75
76/****************************************************************************
77 *
78 * Local function declarations
79 *
80 ***************************************************************************/
81
82static void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
83static void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
84static void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes);
85static FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes);
86static FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes);
87static FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes);
88
89static FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator);
90static FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block);
91static FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length);
92static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block);
93static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block);
94static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length);
95static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length);
96static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length);
97static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry);
98static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment *block);
99static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track);
100static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block);
101static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block);
102static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length);
103
104static FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
105static FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
106static FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block);
107static FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block);
108static FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block);
109static FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length);
110static FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length);
111static FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block);
112static FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block);
113static FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block);
114static FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block);
115static FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length);
116
117static FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block);
118static FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last);
119static FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append);
120
121static void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator);
122static FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator);
123
124static unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb);
125static unsigned seek_to_first_metadata_block_(FILE *f);
126
127static FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append);
128static FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, off_t fixup_is_last_flag_offset, FLAC__bool backup);
129
130static FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status);
131static FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status);
132static FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status);
133static FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status);
134
135static FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
136static FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
137static void cleanup_tempfile_(FILE **tempfile, char **tempfilename);
138
139static FLAC__bool get_file_stats_(const char *filename, struct stat *stats);
140static void set_file_stats_(const char *filename, struct stat *stats);
141
142static int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence);
143static FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle);
144
145static FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status);
146
147
148#ifdef FLAC__VALGRIND_TESTING
149static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
150{
151   size_t ret = fwrite(ptr, size, nmemb, stream);
152   if(!ferror(stream))
153      fflush(stream);
154   return ret;
155}
156#else
157#define local__fwrite fwrite
158#endif
159
160/****************************************************************************
161 *
162 * Level 0 implementation
163 *
164 ***************************************************************************/
165
166static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
167static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
168static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
169
170typedef struct {
171   FLAC__bool got_error;
172   FLAC__StreamMetadata *object;
173} level0_client_data;
174
175static FLAC__StreamMetadata *get_one_metadata_block_(const char *filename, FLAC__MetadataType type)
176{
177   level0_client_data cd;
178   FLAC__StreamDecoder *decoder;
179
180   FLAC__ASSERT(0 != filename);
181
182   cd.got_error = false;
183   cd.object = 0;
184
185   decoder = FLAC__stream_decoder_new();
186
187   if(0 == decoder)
188      return 0;
189
190   FLAC__stream_decoder_set_md5_checking(decoder, false);
191   FLAC__stream_decoder_set_metadata_ignore_all(decoder);
192   FLAC__stream_decoder_set_metadata_respond(decoder, type);
193
194   if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &cd) != FLAC__STREAM_DECODER_INIT_STATUS_OK || cd.got_error) {
195      (void)FLAC__stream_decoder_finish(decoder);
196      FLAC__stream_decoder_delete(decoder);
197      return 0;
198   }
199
200   if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || cd.got_error) {
201      (void)FLAC__stream_decoder_finish(decoder);
202      FLAC__stream_decoder_delete(decoder);
203      if(0 != cd.object)
204         FLAC__metadata_object_delete(cd.object);
205      return 0;
206   }
207
208   (void)FLAC__stream_decoder_finish(decoder);
209   FLAC__stream_decoder_delete(decoder);
210
211   return cd.object;
212}
213
214FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo)
215{
216   FLAC__StreamMetadata *object;
217
218   FLAC__ASSERT(0 != filename);
219   FLAC__ASSERT(0 != streaminfo);
220
221   object = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_STREAMINFO);
222
223   if (object) {
224      /* can just copy the contents since STREAMINFO has no internal structure */
225      *streaminfo = *object;
226      FLAC__metadata_object_delete(object);
227      return true;
228   }
229   else {
230      return false;
231   }
232}
233
234FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags)
235{
236   FLAC__ASSERT(0 != filename);
237   FLAC__ASSERT(0 != tags);
238
239   *tags = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_VORBIS_COMMENT);
240
241   return 0 != *tags;
242}
243
244FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet)
245{
246   FLAC__ASSERT(0 != filename);
247   FLAC__ASSERT(0 != cuesheet);
248
249   *cuesheet = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_CUESHEET);
250
251   return 0 != *cuesheet;
252}
253
254FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
255{
256   (void)decoder, (void)frame, (void)buffer, (void)client_data;
257
258   return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
259}
260
261void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
262{
263   level0_client_data *cd = (level0_client_data *)client_data;
264   (void)decoder;
265
266   /*
267    * we assume we only get here when the one metadata block we were
268    * looking for was passed to us
269    */
270   if(!cd->got_error && 0 == cd->object) {
271      if(0 == (cd->object = FLAC__metadata_object_clone(metadata)))
272         cd->got_error = true;
273   }
274}
275
276void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
277{
278   level0_client_data *cd = (level0_client_data *)client_data;
279   (void)decoder;
280
281   if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC)
282      cd->got_error = true;
283}
284
285FLAC_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)
286{
287   FLAC__Metadata_SimpleIterator *it;
288   FLAC__uint64 max_area_seen = 0;
289   FLAC__uint64 max_depth_seen = 0;
290
291   FLAC__ASSERT(0 != filename);
292   FLAC__ASSERT(0 != picture);
293
294   *picture = 0;
295
296   it = FLAC__metadata_simple_iterator_new();
297   if(0 == it)
298      return false;
299   if(!FLAC__metadata_simple_iterator_init(it, filename, /*read_only=*/true, /*preserve_file_stats=*/true)) {
300      FLAC__metadata_simple_iterator_delete(it);
301      return false;
302   }
303   do {
304      if(FLAC__metadata_simple_iterator_get_block_type(it) == FLAC__METADATA_TYPE_PICTURE) {
305         FLAC__StreamMetadata *obj = FLAC__metadata_simple_iterator_get_block(it);
306         FLAC__uint64 area = (FLAC__uint64)obj->data.picture.width * (FLAC__uint64)obj->data.picture.height;
307         /* check constraints */
308         if(
309            (type == (FLAC__StreamMetadata_Picture_Type)(-1) || type == obj->data.picture.type) &&
310            (mime_type == 0 || !strcmp(mime_type, obj->data.picture.mime_type)) &&
311            (description == 0 || !strcmp((const char *)description, (const char *)obj->data.picture.description)) &&
312            obj->data.picture.width <= max_width &&
313            obj->data.picture.height <= max_height &&
314            obj->data.picture.depth <= max_depth &&
315            obj->data.picture.colors <= max_colors &&
316            (area > max_area_seen || (area == max_area_seen && obj->data.picture.depth > max_depth_seen))
317         ) {
318            if(*picture)
319               FLAC__metadata_object_delete(*picture);
320            *picture = obj;
321            max_area_seen = area;
322            max_depth_seen = obj->data.picture.depth;
323         }
324         else {
325            FLAC__metadata_object_delete(obj);
326         }
327      }
328   } while(FLAC__metadata_simple_iterator_next(it));
329
330   FLAC__metadata_simple_iterator_delete(it);
331
332   return (0 != *picture);
333}
334
335
336/****************************************************************************
337 *
338 * Level 1 implementation
339 *
340 ***************************************************************************/
341
342#define SIMPLE_ITERATOR_MAX_PUSH_DEPTH (1+4)
343/* 1 for initial offset, +4 for our own personal use */
344
345struct FLAC__Metadata_SimpleIterator {
346   FILE *file;
347   char *filename, *tempfile_path_prefix;
348   struct stat stats;
349   FLAC__bool has_stats;
350   FLAC__bool is_writable;
351   FLAC__Metadata_SimpleIteratorStatus status;
352   off_t offset[SIMPLE_ITERATOR_MAX_PUSH_DEPTH];
353   off_t first_offset; /* this is the offset to the STREAMINFO block */
354   unsigned depth;
355   /* this is the metadata block header of the current block we are pointing to: */
356   FLAC__bool is_last;
357   FLAC__MetadataType type;
358   unsigned length;
359};
360
361FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[] = {
362   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK",
363   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT",
364   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE",
365   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE",
366   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE",
367   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA",
368   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR",
369   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR",
370   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR",
371   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR",
372   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR",
373   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR",
374   "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR"
375};
376
377
378FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void)
379{
380   FLAC__Metadata_SimpleIterator *iterator = (FLAC__Metadata_SimpleIterator*)calloc(1, sizeof(FLAC__Metadata_SimpleIterator));
381
382   if(0 != iterator) {
383      iterator->file = 0;
384      iterator->filename = 0;
385      iterator->tempfile_path_prefix = 0;
386      iterator->has_stats = false;
387      iterator->is_writable = false;
388      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
389      iterator->first_offset = iterator->offset[0] = -1;
390      iterator->depth = 0;
391   }
392
393   return iterator;
394}
395
396static void simple_iterator_free_guts_(FLAC__Metadata_SimpleIterator *iterator)
397{
398   FLAC__ASSERT(0 != iterator);
399
400   if(0 != iterator->file) {
401      fclose(iterator->file);
402      iterator->file = 0;
403      if(iterator->has_stats)
404         set_file_stats_(iterator->filename, &iterator->stats);
405   }
406   if(0 != iterator->filename) {
407      free(iterator->filename);
408      iterator->filename = 0;
409   }
410   if(0 != iterator->tempfile_path_prefix) {
411      free(iterator->tempfile_path_prefix);
412      iterator->tempfile_path_prefix = 0;
413   }
414}
415
416FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator)
417{
418   FLAC__ASSERT(0 != iterator);
419
420   simple_iterator_free_guts_(iterator);
421   free(iterator);
422}
423
424FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator)
425{
426   FLAC__Metadata_SimpleIteratorStatus status;
427
428   FLAC__ASSERT(0 != iterator);
429
430   status = iterator->status;
431   iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
432   return status;
433}
434
435static FLAC__bool simple_iterator_prime_input_(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool read_only)
436{
437   unsigned ret;
438
439   FLAC__ASSERT(0 != iterator);
440
441   if(read_only || 0 == (iterator->file = fopen(iterator->filename, "r+b"))) {
442      iterator->is_writable = false;
443      if(read_only || errno == EACCES) {
444         if(0 == (iterator->file = fopen(iterator->filename, "rb"))) {
445            iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
446            return false;
447         }
448      }
449      else {
450         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
451         return false;
452      }
453   }
454   else {
455      iterator->is_writable = true;
456   }
457
458   ret = seek_to_first_metadata_block_(iterator->file);
459   switch(ret) {
460      case 0:
461         iterator->depth = 0;
462         iterator->first_offset = iterator->offset[iterator->depth] = ftello(iterator->file);
463         return read_metadata_block_header_(iterator);
464      case 1:
465         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
466         return false;
467      case 2:
468         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
469         return false;
470      case 3:
471         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE;
472         return false;
473      default:
474         FLAC__ASSERT(0);
475         return false;
476   }
477}
478
479#if 0
480@@@ If we decide to finish implementing this, put this comment back in metadata.h
481/*
482 * The 'tempfile_path_prefix' allows you to specify a directory where
483 * tempfiles should go.  Remember that if your metadata edits cause the
484 * FLAC file to grow, the entire file will have to be rewritten.  If
485 * 'tempfile_path_prefix' is NULL, the temp file will be written in the
486 * same directory as the original FLAC file.  This makes replacing the
487 * original with the tempfile fast but requires extra space in the same
488 * partition for the tempfile.  If space is a problem, you can pass a
489 * directory name belonging to a different partition in
490 * 'tempfile_path_prefix'.  Note that you should use the forward slash
491 * '/' as the directory separator.  A trailing slash is not needed; it
492 * will be added automatically.
493 */
494FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool preserve_file_stats, const char *tempfile_path_prefix);
495#endif
496
497FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats)
498{
499   const char *tempfile_path_prefix = 0; /*@@@ search for comments near 'rename(...)' for what it will take to finish implementing this */
500
501   FLAC__ASSERT(0 != iterator);
502   FLAC__ASSERT(0 != filename);
503
504   simple_iterator_free_guts_(iterator);
505
506   if(!read_only && preserve_file_stats)
507      iterator->has_stats = get_file_stats_(filename, &iterator->stats);
508
509   if(0 == (iterator->filename = strdup(filename))) {
510      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
511      return false;
512   }
513   if(0 != tempfile_path_prefix && 0 == (iterator->tempfile_path_prefix = strdup(tempfile_path_prefix))) {
514      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
515      return false;
516   }
517
518   return simple_iterator_prime_input_(iterator, read_only);
519}
520
521FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator)
522{
523   FLAC__ASSERT(0 != iterator);
524   FLAC__ASSERT(0 != iterator->file);
525
526   return iterator->is_writable;
527}
528
529FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator)
530{
531   FLAC__ASSERT(0 != iterator);
532   FLAC__ASSERT(0 != iterator->file);
533
534   if(iterator->is_last)
535      return false;
536
537   if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) {
538      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
539      return false;
540   }
541
542   iterator->offset[iterator->depth] = ftello(iterator->file);
543
544   return read_metadata_block_header_(iterator);
545}
546
547FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator)
548{
549   off_t this_offset;
550
551   FLAC__ASSERT(0 != iterator);
552   FLAC__ASSERT(0 != iterator->file);
553
554   if(iterator->offset[iterator->depth] == iterator->first_offset)
555      return false;
556
557   if(0 != fseeko(iterator->file, iterator->first_offset, SEEK_SET)) {
558      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
559      return false;
560   }
561   this_offset = iterator->first_offset;
562   if(!read_metadata_block_header_(iterator))
563      return false;
564
565   /* we ignore any error from ftello() and catch it in fseeko() */
566   while(ftello(iterator->file) + (off_t)iterator->length < iterator->offset[iterator->depth]) {
567      if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) {
568         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
569         return false;
570      }
571      this_offset = ftello(iterator->file);
572      if(!read_metadata_block_header_(iterator))
573         return false;
574   }
575
576   iterator->offset[iterator->depth] = this_offset;
577
578   return true;
579}
580
581/*@@@@add to tests*/
582FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator)
583{
584   FLAC__ASSERT(0 != iterator);
585   FLAC__ASSERT(0 != iterator->file);
586
587   return iterator->is_last;
588}
589
590/*@@@@add to tests*/
591FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator)
592{
593   FLAC__ASSERT(0 != iterator);
594   FLAC__ASSERT(0 != iterator->file);
595
596   return iterator->offset[iterator->depth];
597}
598
599FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator)
600{
601   FLAC__ASSERT(0 != iterator);
602   FLAC__ASSERT(0 != iterator->file);
603
604   return iterator->type;
605}
606
607/*@@@@add to tests*/
608FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator)
609{
610   FLAC__ASSERT(0 != iterator);
611   FLAC__ASSERT(0 != iterator->file);
612
613   return iterator->length;
614}
615
616/*@@@@add to tests*/
617FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id)
618{
619   const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
620
621   FLAC__ASSERT(0 != iterator);
622   FLAC__ASSERT(0 != iterator->file);
623   FLAC__ASSERT(0 != id);
624
625   if(iterator->type != FLAC__METADATA_TYPE_APPLICATION) {
626      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
627      return false;
628   }
629
630   if(fread(id, 1, id_bytes, iterator->file) != id_bytes) {
631      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
632      return false;
633   }
634
635   /* back up */
636   if(0 != fseeko(iterator->file, -((int)id_bytes), SEEK_CUR)) {
637      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
638      return false;
639   }
640
641   return true;
642}
643
644FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator)
645{
646   FLAC__StreamMetadata *block = FLAC__metadata_object_new(iterator->type);
647
648   FLAC__ASSERT(0 != iterator);
649   FLAC__ASSERT(0 != iterator->file);
650
651   if(0 != block) {
652      block->is_last = iterator->is_last;
653      block->length = iterator->length;
654
655      if(!read_metadata_block_data_(iterator, block)) {
656         FLAC__metadata_object_delete(block);
657         return 0;
658      }
659
660      /* back up to the beginning of the block data to stay consistent */
661      if(0 != fseeko(iterator->file, iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH, SEEK_SET)) {
662         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
663         FLAC__metadata_object_delete(block);
664         return 0;
665      }
666   }
667   else
668      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
669
670   return block;
671}
672
673FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
674{
675   FLAC__ASSERT_DECLARATION(off_t debug_target_offset = iterator->offset[iterator->depth];)
676   FLAC__bool ret;
677
678   FLAC__ASSERT(0 != iterator);
679   FLAC__ASSERT(0 != iterator->file);
680   FLAC__ASSERT(0 != block);
681
682   if(!iterator->is_writable) {
683      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE;
684      return false;
685   }
686
687   if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO || block->type == FLAC__METADATA_TYPE_STREAMINFO) {
688      if(iterator->type != block->type) {
689         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
690         return false;
691      }
692   }
693
694   block->is_last = iterator->is_last;
695
696   if(iterator->length == block->length)
697      return write_metadata_block_stationary_(iterator, block);
698   else if(iterator->length > block->length) {
699      if(use_padding && iterator->length >= FLAC__STREAM_METADATA_HEADER_LENGTH + block->length) {
700         ret = write_metadata_block_stationary_with_padding_(iterator, block, iterator->length - FLAC__STREAM_METADATA_HEADER_LENGTH - block->length, block->is_last);
701         FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
702         FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
703         return ret;
704      }
705      else {
706         ret = rewrite_whole_file_(iterator, block, /*append=*/false);
707         FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
708         FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
709         return ret;
710      }
711   }
712   else /* iterator->length < block->length */ {
713      unsigned padding_leftover = 0;
714      FLAC__bool padding_is_last = false;
715      if(use_padding) {
716         /* first see if we can even use padding */
717         if(iterator->is_last) {
718            use_padding = false;
719         }
720         else {
721            const unsigned extra_padding_bytes_required = block->length - iterator->length;
722            simple_iterator_push_(iterator);
723            if(!FLAC__metadata_simple_iterator_next(iterator)) {
724               (void)simple_iterator_pop_(iterator);
725               return false;
726            }
727            if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
728               use_padding = false;
729            }
730            else {
731               if(FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length == extra_padding_bytes_required) {
732                  padding_leftover = 0;
733                  block->is_last = iterator->is_last;
734               }
735               else if(iterator->length < extra_padding_bytes_required)
736                  use_padding = false;
737               else {
738                  padding_leftover = FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length - extra_padding_bytes_required;
739                  padding_is_last = iterator->is_last;
740                  block->is_last = false;
741               }
742            }
743            if(!simple_iterator_pop_(iterator))
744               return false;
745         }
746      }
747      if(use_padding) {
748         if(padding_leftover == 0) {
749            ret = write_metadata_block_stationary_(iterator, block);
750            FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
751            FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
752            return ret;
753         }
754         else {
755            FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
756            ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
757            FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
758            FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
759            return ret;
760         }
761      }
762      else {
763         ret = rewrite_whole_file_(iterator, block, /*append=*/false);
764         FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
765         FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
766         return ret;
767      }
768   }
769}
770
771FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
772{
773   unsigned padding_leftover = 0;
774   FLAC__bool padding_is_last = false;
775
776   FLAC__ASSERT_DECLARATION(off_t debug_target_offset = iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length;)
777   FLAC__bool ret;
778
779   FLAC__ASSERT(0 != iterator);
780   FLAC__ASSERT(0 != iterator->file);
781   FLAC__ASSERT(0 != block);
782
783   if(!iterator->is_writable)
784      return false;
785
786   if(block->type == FLAC__METADATA_TYPE_STREAMINFO) {
787      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
788      return false;
789   }
790
791   block->is_last = iterator->is_last;
792
793   if(use_padding) {
794      /* first see if we can even use padding */
795      if(iterator->is_last) {
796         use_padding = false;
797      }
798      else {
799         simple_iterator_push_(iterator);
800         if(!FLAC__metadata_simple_iterator_next(iterator)) {
801            (void)simple_iterator_pop_(iterator);
802            return false;
803         }
804         if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
805            use_padding = false;
806         }
807         else {
808            if(iterator->length == block->length) {
809               padding_leftover = 0;
810               block->is_last = iterator->is_last;
811            }
812            else if(iterator->length < FLAC__STREAM_METADATA_HEADER_LENGTH + block->length)
813               use_padding = false;
814            else {
815               padding_leftover = iterator->length - block->length;
816               padding_is_last = iterator->is_last;
817               block->is_last = false;
818            }
819         }
820         if(!simple_iterator_pop_(iterator))
821            return false;
822      }
823   }
824   if(use_padding) {
825      /* move to the next block, which is suitable padding */
826      if(!FLAC__metadata_simple_iterator_next(iterator))
827         return false;
828      if(padding_leftover == 0) {
829         ret = write_metadata_block_stationary_(iterator, block);
830         FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
831         FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
832         return ret;
833      }
834      else {
835         FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
836         ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
837         FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
838         FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
839         return ret;
840      }
841   }
842   else {
843      ret = rewrite_whole_file_(iterator, block, /*append=*/true);
844      FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
845      FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
846      return ret;
847   }
848}
849
850FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding)
851{
852   FLAC__ASSERT_DECLARATION(off_t debug_target_offset = iterator->offset[iterator->depth];)
853   FLAC__bool ret;
854
855   if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO) {
856      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
857      return false;
858   }
859
860   if(use_padding) {
861      FLAC__StreamMetadata *padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
862      if(0 == padding) {
863         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
864         return false;
865      }
866      padding->length = iterator->length;
867      if(!FLAC__metadata_simple_iterator_set_block(iterator, padding, false)) {
868         FLAC__metadata_object_delete(padding);
869         return false;
870      }
871      FLAC__metadata_object_delete(padding);
872      if(!FLAC__metadata_simple_iterator_prev(iterator))
873         return false;
874      FLAC__ASSERT(iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length == debug_target_offset);
875      FLAC__ASSERT(ftello(iterator->file) + (off_t)iterator->length == debug_target_offset);
876      return true;
877   }
878   else {
879      ret = rewrite_whole_file_(iterator, 0, /*append=*/false);
880      FLAC__ASSERT(iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length == debug_target_offset);
881      FLAC__ASSERT(ftello(iterator->file) + (off_t)iterator->length == debug_target_offset);
882      return ret;
883   }
884}
885
886
887
888/****************************************************************************
889 *
890 * Level 2 implementation
891 *
892 ***************************************************************************/
893
894
895typedef struct FLAC__Metadata_Node {
896   FLAC__StreamMetadata *data;
897   struct FLAC__Metadata_Node *prev, *next;
898} FLAC__Metadata_Node;
899
900struct FLAC__Metadata_Chain {
901   char *filename; /* will be NULL if using callbacks */
902   FLAC__bool is_ogg;
903   FLAC__Metadata_Node *head;
904   FLAC__Metadata_Node *tail;
905   unsigned nodes;
906   FLAC__Metadata_ChainStatus status;
907   off_t first_offset, last_offset;
908   /*
909    * This is the length of the chain initially read from the FLAC file.
910    * it is used to compare against the current length to decide whether
911    * or not the whole file has to be rewritten.
912    */
913   off_t initial_length;
914   /* @@@ hacky, these are currently only needed by ogg reader */
915   FLAC__IOHandle handle;
916   FLAC__IOCallback_Read read_cb;
917};
918
919struct FLAC__Metadata_Iterator {
920   FLAC__Metadata_Chain *chain;
921   FLAC__Metadata_Node *current;
922};
923
924FLAC_API const char * const FLAC__Metadata_ChainStatusString[] = {
925   "FLAC__METADATA_CHAIN_STATUS_OK",
926   "FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT",
927   "FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE",
928   "FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE",
929   "FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE",
930   "FLAC__METADATA_CHAIN_STATUS_BAD_METADATA",
931   "FLAC__METADATA_CHAIN_STATUS_READ_ERROR",
932   "FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR",
933   "FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR",
934   "FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR",
935   "FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR",
936   "FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR",
937   "FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR",
938   "FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS",
939   "FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH",
940   "FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL"
941};
942
943
944static FLAC__Metadata_Node *node_new_(void)
945{
946   return (FLAC__Metadata_Node*)calloc(1, sizeof(FLAC__Metadata_Node));
947}
948
949static void node_delete_(FLAC__Metadata_Node *node)
950{
951   FLAC__ASSERT(0 != node);
952   if(0 != node->data)
953      FLAC__metadata_object_delete(node->data);
954   free(node);
955}
956
957static void chain_init_(FLAC__Metadata_Chain *chain)
958{
959   FLAC__ASSERT(0 != chain);
960
961   chain->filename = 0;
962   chain->is_ogg = false;
963   chain->head = chain->tail = 0;
964   chain->nodes = 0;
965   chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
966   chain->initial_length = 0;
967   chain->read_cb = 0;
968}
969
970static void chain_clear_(FLAC__Metadata_Chain *chain)
971{
972   FLAC__Metadata_Node *node, *next;
973
974   FLAC__ASSERT(0 != chain);
975
976   for(node = chain->head; node; ) {
977      next = node->next;
978      node_delete_(node);
979      node = next;
980   }
981
982   if(0 != chain->filename)
983      free(chain->filename);
984
985   chain_init_(chain);
986}
987
988static void chain_append_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
989{
990   FLAC__ASSERT(0 != chain);
991   FLAC__ASSERT(0 != node);
992   FLAC__ASSERT(0 != node->data);
993
994   node->next = node->prev = 0;
995   node->data->is_last = true;
996   if(0 != chain->tail)
997      chain->tail->data->is_last = false;
998
999   if(0 == chain->head)
1000      chain->head = node;
1001   else {
1002      FLAC__ASSERT(0 != chain->tail);
1003      chain->tail->next = node;
1004      node->prev = chain->tail;
1005   }
1006   chain->tail = node;
1007   chain->nodes++;
1008}
1009
1010static void chain_remove_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
1011{
1012   FLAC__ASSERT(0 != chain);
1013   FLAC__ASSERT(0 != node);
1014
1015   if(node == chain->head)
1016      chain->head = node->next;
1017   else
1018      node->prev->next = node->next;
1019
1020   if(node == chain->tail)
1021      chain->tail = node->prev;
1022   else
1023      node->next->prev = node->prev;
1024
1025   if(0 != chain->tail)
1026      chain->tail->data->is_last = true;
1027
1028   chain->nodes--;
1029}
1030
1031static void chain_delete_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
1032{
1033   chain_remove_node_(chain, node);
1034   node_delete_(node);
1035}
1036
1037static off_t chain_calculate_length_(FLAC__Metadata_Chain *chain)
1038{
1039   const FLAC__Metadata_Node *node;
1040   off_t length = 0;
1041   for(node = chain->head; node; node = node->next)
1042      length += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1043   return length;
1044}
1045
1046static void iterator_insert_node_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
1047{
1048   FLAC__ASSERT(0 != node);
1049   FLAC__ASSERT(0 != node->data);
1050   FLAC__ASSERT(0 != iterator);
1051   FLAC__ASSERT(0 != iterator->current);
1052   FLAC__ASSERT(0 != iterator->chain);
1053   FLAC__ASSERT(0 != iterator->chain->head);
1054   FLAC__ASSERT(0 != iterator->chain->tail);
1055
1056   node->data->is_last = false;
1057
1058   node->prev = iterator->current->prev;
1059   node->next = iterator->current;
1060
1061   if(0 == node->prev)
1062      iterator->chain->head = node;
1063   else
1064      node->prev->next = node;
1065
1066   iterator->current->prev = node;
1067
1068   iterator->chain->nodes++;
1069}
1070
1071static void iterator_insert_node_after_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
1072{
1073   FLAC__ASSERT(0 != node);
1074   FLAC__ASSERT(0 != node->data);
1075   FLAC__ASSERT(0 != iterator);
1076   FLAC__ASSERT(0 != iterator->current);
1077   FLAC__ASSERT(0 != iterator->chain);
1078   FLAC__ASSERT(0 != iterator->chain->head);
1079   FLAC__ASSERT(0 != iterator->chain->tail);
1080
1081   iterator->current->data->is_last = false;
1082
1083   node->prev = iterator->current;
1084   node->next = iterator->current->next;
1085
1086   if(0 == node->next)
1087      iterator->chain->tail = node;
1088   else
1089      node->next->prev = node;
1090
1091   node->prev->next = node;
1092
1093   iterator->chain->tail->data->is_last = true;
1094
1095   iterator->chain->nodes++;
1096}
1097
1098/* return true iff node and node->next are both padding */
1099static FLAC__bool chain_merge_adjacent_padding_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
1100{
1101   if(node->data->type == FLAC__METADATA_TYPE_PADDING && 0 != node->next && node->next->data->type == FLAC__METADATA_TYPE_PADDING) {
1102      const unsigned growth = FLAC__STREAM_METADATA_HEADER_LENGTH + node->next->data->length;
1103      node->data->length += growth;
1104
1105      chain_delete_node_(chain, node->next);
1106      return true;
1107   }
1108   else
1109      return false;
1110}
1111
1112/* Returns the new length of the chain, or 0 if there was an error. */
1113/* WATCHOUT: This can get called multiple times before a write, so
1114 * it should still work when this happens.
1115 */
1116/* WATCHOUT: Make sure to also update the logic in
1117 * FLAC__metadata_chain_check_if_tempfile_needed() if the logic here changes.
1118 */
1119static off_t chain_prepare_for_write_(FLAC__Metadata_Chain *chain, FLAC__bool use_padding)
1120{
1121   off_t current_length = chain_calculate_length_(chain);
1122
1123   if(use_padding) {
1124      /* if the metadata shrank and the last block is padding, we just extend the last padding block */
1125      if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1126         const off_t delta = chain->initial_length - current_length;
1127         chain->tail->data->length += delta;
1128         current_length += delta;
1129         FLAC__ASSERT(current_length == chain->initial_length);
1130      }
1131      /* if the metadata shrank more than 4 bytes then there's room to add another padding block */
1132      else if(current_length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length) {
1133         FLAC__StreamMetadata *padding;
1134         FLAC__Metadata_Node *node;
1135         if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) {
1136            chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1137            return 0;
1138         }
1139         padding->length = chain->initial_length - (FLAC__STREAM_METADATA_HEADER_LENGTH + current_length);
1140         if(0 == (node = node_new_())) {
1141            FLAC__metadata_object_delete(padding);
1142            chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1143            return 0;
1144         }
1145         node->data = padding;
1146         chain_append_node_(chain, node);
1147         current_length = chain_calculate_length_(chain);
1148         FLAC__ASSERT(current_length == chain->initial_length);
1149      }
1150      /* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */
1151      else if(current_length > chain->initial_length) {
1152         const off_t delta = current_length - chain->initial_length;
1153         if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1154            /* if the delta is exactly the size of the last padding block, remove the padding block */
1155            if((off_t)chain->tail->data->length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta) {
1156               chain_delete_node_(chain, chain->tail);
1157               current_length = chain_calculate_length_(chain);
1158               FLAC__ASSERT(current_length == chain->initial_length);
1159            }
1160            /* if there is at least 'delta' bytes of padding, trim the padding down */
1161            else if((off_t)chain->tail->data->length >= delta) {
1162               chain->tail->data->length -= delta;
1163               current_length -= delta;
1164               FLAC__ASSERT(current_length == chain->initial_length);
1165            }
1166         }
1167      }
1168   }
1169
1170   return current_length;
1171}
1172
1173static FLAC__bool chain_read_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Tell tell_cb)
1174{
1175   FLAC__Metadata_Node *node;
1176
1177   FLAC__ASSERT(0 != chain);
1178
1179   /* we assume we're already at the beginning of the file */
1180
1181   switch(seek_to_first_metadata_block_cb_(handle, read_cb, seek_cb)) {
1182      case 0:
1183         break;
1184      case 1:
1185         chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1186         return false;
1187      case 2:
1188         chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1189         return false;
1190      case 3:
1191         chain->status = FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
1192         return false;
1193      default:
1194         FLAC__ASSERT(0);
1195         return false;
1196   }
1197
1198   {
1199      FLAC__int64 pos = tell_cb(handle);
1200      if(pos < 0) {
1201         chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1202         return false;
1203      }
1204      chain->first_offset = (off_t)pos;
1205   }
1206
1207   {
1208      FLAC__bool is_last;
1209      FLAC__MetadataType type;
1210      unsigned length;
1211
1212      do {
1213         node = node_new_();
1214         if(0 == node) {
1215            chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1216            return false;
1217         }
1218
1219         if(!read_metadata_block_header_cb_(handle, read_cb, &is_last, &type, &length)) {
1220            chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1221            return false;
1222         }
1223
1224         node->data = FLAC__metadata_object_new(type);
1225         if(0 == node->data) {
1226            node_delete_(node);
1227            chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1228            return false;
1229         }
1230
1231         node->data->is_last = is_last;
1232         node->data->length = length;
1233
1234         chain->status = get_equivalent_status_(read_metadata_block_data_cb_(handle, read_cb, seek_cb, node->data));
1235         if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) {
1236            node_delete_(node);
1237            return false;
1238         }
1239         chain_append_node_(chain, node);
1240      } while(!is_last);
1241   }
1242
1243   {
1244      FLAC__int64 pos = tell_cb(handle);
1245      if(pos < 0) {
1246         chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1247         return false;
1248      }
1249      chain->last_offset = (off_t)pos;
1250   }
1251
1252   chain->initial_length = chain_calculate_length_(chain);
1253
1254   return true;
1255}
1256
1257static FLAC__StreamDecoderReadStatus chain_read_ogg_read_cb_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
1258{
1259   FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
1260   (void)decoder;
1261   if(*bytes > 0 && chain->status == FLAC__METADATA_CHAIN_STATUS_OK) {
1262      *bytes = chain->read_cb(buffer, sizeof(FLAC__byte), *bytes, chain->handle);
1263      if(*bytes == 0)
1264         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
1265      else
1266         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
1267   }
1268   else
1269      return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
1270}
1271
1272static FLAC__StreamDecoderWriteStatus chain_read_ogg_write_cb_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
1273{
1274   (void)decoder, (void)frame, (void)buffer, (void)client_data;
1275   return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1276}
1277
1278static void chain_read_ogg_metadata_cb_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1279{
1280   FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
1281   FLAC__Metadata_Node *node;
1282
1283   (void)decoder;
1284
1285   node = node_new_();
1286   if(0 == node) {
1287      chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1288      return;
1289   }
1290
1291   node->data = FLAC__metadata_object_clone(metadata);
1292   if(0 == node->data) {
1293      node_delete_(node);
1294      chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1295      return;
1296   }
1297
1298   chain_append_node_(chain, node);
1299}
1300
1301static void chain_read_ogg_error_cb_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1302{
1303   FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
1304   (void)decoder, (void)status;
1305   chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
1306}
1307
1308static FLAC__bool chain_read_ogg_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb)
1309{
1310   FLAC__StreamDecoder *decoder;
1311
1312   FLAC__ASSERT(0 != chain);
1313
1314   /* we assume we're already at the beginning of the file */
1315
1316   chain->handle = handle;
1317   chain->read_cb = read_cb;
1318   if(0 == (decoder = FLAC__stream_decoder_new())) {
1319      chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1320      return false;
1321   }
1322   FLAC__stream_decoder_set_metadata_respond_all(decoder);
1323   if(FLAC__stream_decoder_init_ogg_stream(decoder, chain_read_ogg_read_cb_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, chain_read_ogg_write_cb_, chain_read_ogg_metadata_cb_, chain_read_ogg_error_cb_, chain) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
1324      FLAC__stream_decoder_delete(decoder);
1325      chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
1326      return false;
1327   }
1328
1329   chain->first_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */
1330
1331   if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder))
1332      chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
1333   if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) {
1334      FLAC__stream_decoder_delete(decoder);
1335      return false;
1336   }
1337
1338   FLAC__stream_decoder_delete(decoder);
1339
1340   chain->last_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */
1341
1342   chain->initial_length = chain_calculate_length_(chain);
1343
1344   return true;
1345}
1346
1347static FLAC__bool chain_rewrite_metadata_in_place_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, FLAC__IOCallback_Seek seek_cb)
1348{
1349   FLAC__Metadata_Node *node;
1350
1351   FLAC__ASSERT(0 != chain);
1352   FLAC__ASSERT(0 != chain->head);
1353
1354   if(0 != seek_cb(handle, chain->first_offset, SEEK_SET)) {
1355      chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1356      return false;
1357   }
1358
1359   for(node = chain->head; node; node = node->next) {
1360      if(!write_metadata_block_header_cb_(handle, write_cb, node->data)) {
1361         chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1362         return false;
1363      }
1364      if(!write_metadata_block_data_cb_(handle, write_cb, node->data)) {
1365         chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1366         return false;
1367      }
1368   }
1369
1370   /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
1371
1372   chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
1373   return true;
1374}
1375
1376static FLAC__bool chain_rewrite_metadata_in_place_(FLAC__Metadata_Chain *chain)
1377{
1378   FILE *file;
1379   FLAC__bool ret;
1380
1381   FLAC__ASSERT(0 != chain->filename);
1382
1383   if(0 == (file = fopen(chain->filename, "r+b"))) {
1384      chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1385      return false;
1386   }
1387
1388   /* chain_rewrite_metadata_in_place_cb_() sets chain->status for us */
1389   ret = chain_rewrite_metadata_in_place_cb_(chain, (FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, fseek_wrapper_);
1390
1391   fclose(file);
1392
1393   return ret;
1394}
1395
1396static FLAC__bool chain_rewrite_file_(FLAC__Metadata_Chain *chain, const char *tempfile_path_prefix)
1397{
1398   FILE *f, *tempfile;
1399   char *tempfilename;
1400   FLAC__Metadata_SimpleIteratorStatus status;
1401   const FLAC__Metadata_Node *node;
1402
1403   FLAC__ASSERT(0 != chain);
1404   FLAC__ASSERT(0 != chain->filename);
1405   FLAC__ASSERT(0 != chain->head);
1406
1407   /* copy the file prefix (data up to first metadata block */
1408   if(0 == (f = fopen(chain->filename, "rb"))) {
1409      chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1410      return false;
1411   }
1412   if(!open_tempfile_(chain->filename, tempfile_path_prefix, &tempfile, &tempfilename, &status)) {
1413      chain->status = get_equivalent_status_(status);
1414      cleanup_tempfile_(&tempfile, &tempfilename);
1415      return false;
1416   }
1417   if(!copy_n_bytes_from_file_(f, tempfile, chain->first_offset, &status)) {
1418      chain->status = get_equivalent_status_(status);
1419      cleanup_tempfile_(&tempfile, &tempfilename);
1420      return false;
1421   }
1422
1423   /* write the metadata */
1424   for(node = chain->head; node; node = node->next) {
1425      if(!write_metadata_block_header_(tempfile, &status, node->data)) {
1426         chain->status = get_equivalent_status_(status);
1427         return false;
1428      }
1429      if(!write_metadata_block_data_(tempfile, &status, node->data)) {
1430         chain->status = get_equivalent_status_(status);
1431         return false;
1432      }
1433   }
1434   /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
1435
1436   /* copy the file postfix (everything after the metadata) */
1437   if(0 != fseeko(f, chain->last_offset, SEEK_SET)) {
1438      cleanup_tempfile_(&tempfile, &tempfilename);
1439      chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1440      return false;
1441   }
1442   if(!copy_remaining_bytes_from_file_(f, tempfile, &status)) {
1443      cleanup_tempfile_(&tempfile, &tempfilename);
1444      chain->status = get_equivalent_status_(status);
1445      return false;
1446   }
1447
1448   /* move the tempfile on top of the original */
1449   (void)fclose(f);
1450   if(!transport_tempfile_(chain->filename, &tempfile, &tempfilename, &status))
1451      return false;
1452
1453   return true;
1454}
1455
1456/* assumes 'handle' is already at beginning of file */
1457static FLAC__bool chain_rewrite_file_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb)
1458{
1459   FLAC__Metadata_SimpleIteratorStatus status;
1460   const FLAC__Metadata_Node *node;
1461
1462   FLAC__ASSERT(0 != chain);
1463   FLAC__ASSERT(0 == chain->filename);
1464   FLAC__ASSERT(0 != chain->head);
1465
1466   /* copy the file prefix (data up to first metadata block */
1467   if(!copy_n_bytes_from_file_cb_(handle, read_cb, temp_handle, temp_write_cb, chain->first_offset, &status)) {
1468      chain->status = get_equivalent_status_(status);
1469      return false;
1470   }
1471
1472   /* write the metadata */
1473   for(node = chain->head; node; node = node->next) {
1474      if(!write_metadata_block_header_cb_(temp_handle, temp_write_cb, node->data)) {
1475         chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1476         return false;
1477      }
1478      if(!write_metadata_block_data_cb_(temp_handle, temp_write_cb, node->data)) {
1479         chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1480         return false;
1481      }
1482   }
1483   /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
1484
1485   /* copy the file postfix (everything after the metadata) */
1486   if(0 != seek_cb(handle, chain->last_offset, SEEK_SET)) {
1487      chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1488      return false;
1489   }
1490   if(!copy_remaining_bytes_from_file_cb_(handle, read_cb, eof_cb, temp_handle, temp_write_cb, &status)) {
1491      chain->status = get_equivalent_status_(status);
1492      return false;
1493   }
1494
1495   return true;
1496}
1497
1498FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void)
1499{
1500   FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)calloc(1, sizeof(FLAC__Metadata_Chain));
1501
1502   if(0 != chain)
1503      chain_init_(chain);
1504
1505   return chain;
1506}
1507
1508FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain)
1509{
1510   FLAC__ASSERT(0 != chain);
1511
1512   chain_clear_(chain);
1513
1514   free(chain);
1515}
1516
1517FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain)
1518{
1519   FLAC__Metadata_ChainStatus status;
1520
1521   FLAC__ASSERT(0 != chain);
1522
1523   status = chain->status;
1524   chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
1525   return status;
1526}
1527
1528static FLAC__bool chain_read_(FLAC__Metadata_Chain *chain, const char *filename, FLAC__bool is_ogg)
1529{
1530   FILE *file;
1531   FLAC__bool ret;
1532
1533   FLAC__ASSERT(0 != chain);
1534   FLAC__ASSERT(0 != filename);
1535
1536   chain_clear_(chain);
1537
1538   if(0 == (chain->filename = strdup(filename))) {
1539      chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1540      return false;
1541   }
1542
1543   chain->is_ogg = is_ogg;
1544
1545   if(0 == (file = fopen(filename, "rb"))) {
1546      chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1547      return false;
1548   }
1549
1550   /* the function also sets chain->status for us */
1551   ret = is_ogg?
1552      chain_read_ogg_cb_(chain, file, (FLAC__IOCallback_Read)fread) :
1553      chain_read_cb_(chain, file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, ftell_wrapper_)
1554   ;
1555
1556   fclose(file);
1557
1558   return ret;
1559}
1560
1561FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename)
1562{
1563   return chain_read_(chain, filename, /*is_ogg=*/false);
1564}
1565
1566/*@@@@add to tests*/
1567FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename)
1568{
1569   return chain_read_(chain, filename, /*is_ogg=*/true);
1570}
1571
1572static FLAC__bool chain_read_with_callbacks_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__bool is_ogg)
1573{
1574   FLAC__bool ret;
1575
1576   FLAC__ASSERT(0 != chain);
1577
1578   chain_clear_(chain);
1579
1580   if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.tell) {
1581      chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1582      return false;
1583   }
1584
1585   chain->is_ogg = is_ogg;
1586
1587   /* rewind */
1588   if(0 != callbacks.seek(handle, 0, SEEK_SET)) {
1589      chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1590      return false;
1591   }
1592
1593   /* the function also sets chain->status for us */
1594   ret = is_ogg?
1595      chain_read_ogg_cb_(chain, handle, callbacks.read) :
1596      chain_read_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.tell)
1597   ;
1598
1599   return ret;
1600}
1601
1602FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
1603{
1604   return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/false);
1605}
1606
1607/*@@@@add to tests*/
1608FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
1609{
1610   return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/true);
1611}
1612
1613FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding)
1614{
1615   /* This does all the same checks that are in chain_prepare_for_write_()
1616    * but doesn't actually alter the chain.  Make sure to update the logic
1617    * here if chain_prepare_for_write_() changes.
1618    */
1619   const off_t current_length = chain_calculate_length_(chain);
1620
1621   FLAC__ASSERT(0 != chain);
1622
1623   if(use_padding) {
1624      /* if the metadata shrank and the last block is padding, we just extend the last padding block */
1625      if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING)
1626         return false;
1627      /* if the metadata shrank more than 4 bytes then there's room to add another padding block */
1628      else if(current_length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length)
1629         return false;
1630      /* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */
1631      else if(current_length > chain->initial_length) {
1632         const off_t delta = current_length - chain->initial_length;
1633         if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1634            /* if the delta is exactly the size of the last padding block, remove the padding block */
1635            if((off_t)chain->tail->data->length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta)
1636               return false;
1637            /* if there is at least 'delta' bytes of padding, trim the padding down */
1638            else if((off_t)chain->tail->data->length >= delta)
1639               return false;
1640         }
1641      }
1642   }
1643
1644   return (current_length != chain->initial_length);
1645}
1646
1647FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats)
1648{
1649   struct stat stats;
1650   const char *tempfile_path_prefix = 0;
1651   off_t current_length;
1652
1653   FLAC__ASSERT(0 != chain);
1654
1655   if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
1656      chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
1657      return false;
1658   }
1659
1660   if (0 == chain->filename) {
1661      chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
1662      return false;
1663   }
1664
1665   current_length = chain_prepare_for_write_(chain, use_padding);
1666
1667   /* a return value of 0 means there was an error; chain->status is already set */
1668   if (0 == current_length)
1669      return false;
1670
1671   if(preserve_file_stats)
1672      get_file_stats_(chain->filename, &stats);
1673
1674   if(current_length == chain->initial_length) {
1675      if(!chain_rewrite_metadata_in_place_(chain))
1676         return false;
1677   }
1678   else {
1679      if(!chain_rewrite_file_(chain, tempfile_path_prefix))
1680         return false;
1681
1682      /* recompute lengths and offsets */
1683      {
1684         const FLAC__Metadata_Node *node;
1685         chain->initial_length = current_length;
1686         chain->last_offset = chain->first_offset;
1687         for(node = chain->head; node; node = node->next)
1688            chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1689      }
1690   }
1691
1692   if(preserve_file_stats)
1693      set_file_stats_(chain->filename, &stats);
1694
1695   return true;
1696}
1697
1698FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
1699{
1700   off_t current_length;
1701
1702   FLAC__ASSERT(0 != chain);
1703
1704   if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
1705      chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
1706      return false;
1707   }
1708
1709   if (0 != chain->filename) {
1710      chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
1711      return false;
1712   }
1713
1714   if (0 == callbacks.write || 0 == callbacks.seek) {
1715      chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1716      return false;
1717   }
1718
1719   if (FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) {
1720      chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL;
1721      return false;
1722   }
1723
1724   current_length = chain_prepare_for_write_(chain, use_padding);
1725
1726   /* a return value of 0 means there was an error; chain->status is already set */
1727   if (0 == current_length)
1728      return false;
1729
1730   FLAC__ASSERT(current_length == chain->initial_length);
1731
1732   return chain_rewrite_metadata_in_place_cb_(chain, handle, callbacks.write, callbacks.seek);
1733}
1734
1735FLAC_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)
1736{
1737   off_t current_length;
1738
1739   FLAC__ASSERT(0 != chain);
1740
1741   if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
1742      chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
1743      return false;
1744   }
1745
1746   if (0 != chain->filename) {
1747      chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
1748      return false;
1749   }
1750
1751   if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.eof) {
1752      chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1753      return false;
1754   }
1755   if (0 == temp_callbacks.write) {
1756      chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1757      return false;
1758   }
1759
1760   if (!FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) {
1761      chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL;
1762      return false;
1763   }
1764
1765   current_length = chain_prepare_for_write_(chain, use_padding);
1766
1767   /* a return value of 0 means there was an error; chain->status is already set */
1768   if (0 == current_length)
1769      return false;
1770
1771   FLAC__ASSERT(current_length != chain->initial_length);
1772
1773   /* rewind */
1774   if(0 != callbacks.seek(handle, 0, SEEK_SET)) {
1775      chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1776      return false;
1777   }
1778
1779   if(!chain_rewrite_file_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.eof, temp_handle, temp_callbacks.write))
1780      return false;
1781
1782   /* recompute lengths and offsets */
1783   {
1784      const FLAC__Metadata_Node *node;
1785      chain->initial_length = current_length;
1786      chain->last_offset = chain->first_offset;
1787      for(node = chain->head; node; node = node->next)
1788         chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1789   }
1790
1791   return true;
1792}
1793
1794FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain)
1795{
1796   FLAC__Metadata_Node *node;
1797
1798   FLAC__ASSERT(0 != chain);
1799
1800   for(node = chain->head; node; ) {
1801      if(!chain_merge_adjacent_padding_(chain, node))
1802         node = node->next;
1803   }
1804}
1805
1806FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain)
1807{
1808   FLAC__Metadata_Node *node, *save;
1809   unsigned i;
1810
1811   FLAC__ASSERT(0 != chain);
1812
1813   /*
1814    * Don't try and be too smart... this simple algo is good enough for
1815    * the small number of nodes that we deal with.
1816    */
1817   for(i = 0, node = chain->head; i < chain->nodes; i++) {
1818      if(node->data->type == FLAC__METADATA_TYPE_PADDING) {
1819         save = node->next;
1820         chain_remove_node_(chain, node);
1821         chain_append_node_(chain, node);
1822         node = save;
1823      }
1824      else {
1825         node = node->next;
1826      }
1827   }
1828
1829   FLAC__metadata_chain_merge_padding(chain);
1830}
1831
1832
1833FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void)
1834{
1835   FLAC__Metadata_Iterator *iterator = (FLAC__Metadata_Iterator*)calloc(1, sizeof(FLAC__Metadata_Iterator));
1836
1837   /* calloc() implies:
1838      iterator->current = 0;
1839      iterator->chain = 0;
1840   */
1841
1842   return iterator;
1843}
1844
1845FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator)
1846{
1847   FLAC__ASSERT(0 != iterator);
1848
1849   free(iterator);
1850}
1851
1852FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain)
1853{
1854   FLAC__ASSERT(0 != iterator);
1855   FLAC__ASSERT(0 != chain);
1856   FLAC__ASSERT(0 != chain->head);
1857
1858   iterator->chain = chain;
1859   iterator->current = chain->head;
1860}
1861
1862FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator)
1863{
1864   FLAC__ASSERT(0 != iterator);
1865
1866   if(0 == iterator->current || 0 == iterator->current->next)
1867      return false;
1868
1869   iterator->current = iterator->current->next;
1870   return true;
1871}
1872
1873FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator)
1874{
1875   FLAC__ASSERT(0 != iterator);
1876
1877   if(0 == iterator->current || 0 == iterator->current->prev)
1878      return false;
1879
1880   iterator->current = iterator->current->prev;
1881   return true;
1882}
1883
1884FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator)
1885{
1886   FLAC__ASSERT(0 != iterator);
1887   FLAC__ASSERT(0 != iterator->current);
1888   FLAC__ASSERT(0 != iterator->current->data);
1889
1890   return iterator->current->data->type;
1891}
1892
1893FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator)
1894{
1895   FLAC__ASSERT(0 != iterator);
1896   FLAC__ASSERT(0 != iterator->current);
1897
1898   return iterator->current->data;
1899}
1900
1901FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1902{
1903   FLAC__ASSERT(0 != iterator);
1904   FLAC__ASSERT(0 != block);
1905   return FLAC__metadata_iterator_delete_block(iterator, false) && FLAC__metadata_iterator_insert_block_after(iterator, block);
1906}
1907
1908FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding)
1909{
1910   FLAC__Metadata_Node *save;
1911
1912   FLAC__ASSERT(0 != iterator);
1913   FLAC__ASSERT(0 != iterator->current);
1914
1915   if(0 == iterator->current->prev) {
1916      FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1917      return false;
1918   }
1919
1920   save = iterator->current->prev;
1921
1922   if(replace_with_padding) {
1923      FLAC__metadata_object_delete_data(iterator->current->data);
1924      iterator->current->data->type = FLAC__METADATA_TYPE_PADDING;
1925   }
1926   else {
1927      chain_delete_node_(iterator->chain, iterator->current);
1928   }
1929
1930   iterator->current = save;
1931   return true;
1932}
1933
1934FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1935{
1936   FLAC__Metadata_Node *node;
1937
1938   FLAC__ASSERT(0 != iterator);
1939   FLAC__ASSERT(0 != iterator->current);
1940   FLAC__ASSERT(0 != block);
1941
1942   if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1943      return false;
1944
1945   if(0 == iterator->current->prev) {
1946      FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1947      return false;
1948   }
1949
1950   if(0 == (node = node_new_()))
1951      return false;
1952
1953   node->data = block;
1954   iterator_insert_node_(iterator, node);
1955   iterator->current = node;
1956   return true;
1957}
1958
1959FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1960{
1961   FLAC__Metadata_Node *node;
1962
1963   FLAC__ASSERT(0 != iterator);
1964   FLAC__ASSERT(0 != iterator->current);
1965   FLAC__ASSERT(0 != block);
1966
1967   if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1968      return false;
1969
1970   if(0 == (node = node_new_()))
1971      return false;
1972
1973   node->data = block;
1974   iterator_insert_node_after_(iterator, node);
1975   iterator->current = node;
1976   return true;
1977}
1978
1979
1980/****************************************************************************
1981 *
1982 * Local function definitions
1983 *
1984 ***************************************************************************/
1985
1986void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1987{
1988   unsigned i;
1989
1990   b += bytes;
1991
1992   for(i = 0; i < bytes; i++) {
1993      *(--b) = (FLAC__byte)(val & 0xff);
1994      val >>= 8;
1995   }
1996}
1997
1998void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1999{
2000   unsigned i;
2001
2002   for(i = 0; i < bytes; i++) {
2003      *(b++) = (FLAC__byte)(val & 0xff);
2004      val >>= 8;
2005   }
2006}
2007
2008void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes)
2009{
2010   unsigned i;
2011
2012   b += bytes;
2013
2014   for(i = 0; i < bytes; i++) {
2015      *(--b) = (FLAC__byte)(val & 0xff);
2016      val >>= 8;
2017   }
2018}
2019
2020FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes)
2021{
2022   FLAC__uint32 ret = 0;
2023   unsigned i;
2024
2025   for(i = 0; i < bytes; i++)
2026      ret = (ret << 8) | (FLAC__uint32)(*b++);
2027
2028   return ret;
2029}
2030
2031FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes)
2032{
2033   FLAC__uint32 ret = 0;
2034   unsigned i;
2035
2036   b += bytes;
2037
2038   for(i = 0; i < bytes; i++)
2039      ret = (ret << 8) | (FLAC__uint32)(*--b);
2040
2041   return ret;
2042}
2043
2044FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes)
2045{
2046   FLAC__uint64 ret = 0;
2047   unsigned i;
2048
2049   for(i = 0; i < bytes; i++)
2050      ret = (ret << 8) | (FLAC__uint64)(*b++);
2051
2052   return ret;
2053}
2054
2055FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator)
2056{
2057   FLAC__ASSERT(0 != iterator);
2058   FLAC__ASSERT(0 != iterator->file);
2059
2060   if(!read_metadata_block_header_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, &iterator->is_last, &iterator->type, &iterator->length)) {
2061      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2062      return false;
2063   }
2064
2065   return true;
2066}
2067
2068FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block)
2069{
2070   FLAC__ASSERT(0 != iterator);
2071   FLAC__ASSERT(0 != iterator->file);
2072
2073   iterator->status = read_metadata_block_data_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, block);
2074
2075   return (iterator->status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK);
2076}
2077
2078FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length)
2079{
2080   FLAC__byte raw_header[FLAC__STREAM_METADATA_HEADER_LENGTH];
2081
2082   if(read_cb(raw_header, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH)
2083      return false;
2084
2085   *is_last = raw_header[0] & 0x80? true : false;
2086   *type = (FLAC__MetadataType)(raw_header[0] & 0x7f);
2087   *length = unpack_uint32_(raw_header + 1, 3);
2088
2089   /* Note that we don't check:
2090    *    if(iterator->type >= FLAC__METADATA_TYPE_UNDEFINED)
2091    * we just will read in an opaque block
2092    */
2093
2094   return true;
2095}
2096
2097FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block)
2098{
2099   switch(block->type) {
2100      case FLAC__METADATA_TYPE_STREAMINFO:
2101         return read_metadata_block_data_streaminfo_cb_(handle, read_cb, &block->data.stream_info);
2102      case FLAC__METADATA_TYPE_PADDING:
2103         return read_metadata_block_data_padding_cb_(handle, seek_cb, &block->data.padding, block->length);
2104      case FLAC__METADATA_TYPE_APPLICATION:
2105         return read_metadata_block_data_application_cb_(handle, read_cb, &block->data.application, block->length);
2106      case FLAC__METADATA_TYPE_SEEKTABLE:
2107         return read_metadata_block_data_seektable_cb_(handle, read_cb, &block->data.seek_table, block->length);
2108      case FLAC__METADATA_TYPE_VORBIS_COMMENT:
2109         return read_metadata_block_data_vorbis_comment_cb_(handle, read_cb, &block->data.vorbis_comment);
2110      case FLAC__METADATA_TYPE_CUESHEET:
2111         return read_metadata_block_data_cuesheet_cb_(handle, read_cb, &block->data.cue_sheet);
2112      case FLAC__METADATA_TYPE_PICTURE:
2113         return read_metadata_block_data_picture_cb_(handle, read_cb, &block->data.picture);
2114      default:
2115         return read_metadata_block_data_unknown_cb_(handle, read_cb, &block->data.unknown, block->length);
2116   }
2117}
2118
2119FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block)
2120{
2121   FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH], *b;
2122
2123   if(read_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
2124      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2125
2126   b = buffer;
2127
2128   /* we are using hardcoded numbers for simplicity but we should
2129    * probably eventually write a bit-level unpacker and use the
2130    * _STREAMINFO_ constants.
2131    */
2132   block->min_blocksize = unpack_uint32_(b, 2); b += 2;
2133   block->max_blocksize = unpack_uint32_(b, 2); b += 2;
2134   block->min_framesize = unpack_uint32_(b, 3); b += 3;
2135   block->max_framesize = unpack_uint32_(b, 3); b += 3;
2136   block->sample_rate = (unpack_uint32_(b, 2) << 4) | ((unsigned)(b[2] & 0xf0) >> 4);
2137   block->channels = (unsigned)((b[2] & 0x0e) >> 1) + 1;
2138   block->bits_per_sample = ((((unsigned)(b[2] & 0x01)) << 4) | (((unsigned)(b[3] & 0xf0)) >> 4)) + 1;
2139   block->total_samples = (((FLAC__uint64)(b[3] & 0x0f)) << 32) | unpack_uint64_(b+4, 4);
2140   memcpy(block->md5sum, b+8, 16);
2141
2142   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2143}
2144
2145FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length)
2146{
2147   (void)block; /* nothing to do; we don't care about reading the padding bytes */
2148
2149   if(0 != seek_cb(handle, block_length, SEEK_CUR))
2150      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2151
2152   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2153}
2154
2155FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length)
2156{
2157   const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
2158
2159   if(read_cb(block->id, 1, id_bytes, handle) != id_bytes)
2160      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2161
2162   if(block_length < id_bytes)
2163      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2164
2165   block_length -= id_bytes;
2166
2167   if(block_length == 0) {
2168      block->data = 0;
2169   }
2170   else {
2171      if(0 == (block->data = (FLAC__byte*)malloc(block_length)))
2172         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2173
2174      if(read_cb(block->data, 1, block_length, handle) != block_length)
2175         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2176   }
2177
2178   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2179}
2180
2181FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length)
2182{
2183   unsigned i;
2184   FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
2185
2186   FLAC__ASSERT(block_length % FLAC__STREAM_METADATA_SEEKPOINT_LENGTH == 0);
2187
2188   block->num_points = block_length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
2189
2190   if(block->num_points == 0)
2191      block->points = 0;
2192   else if(0 == (block->points = (FLAC__StreamMetadata_SeekPoint*)safe_malloc_mul_2op_(block->num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint))))
2193      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2194
2195   for(i = 0; i < block->num_points; i++) {
2196      if(read_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
2197         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2198      /* some MAGIC NUMBERs here */
2199      block->points[i].sample_number = unpack_uint64_(buffer, 8);
2200      block->points[i].stream_offset = unpack_uint64_(buffer+8, 8);
2201      block->points[i].frame_samples = unpack_uint32_(buffer+16, 2);
2202   }
2203
2204   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2205}
2206
2207FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry)
2208{
2209   const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
2210   FLAC__byte buffer[4]; /* magic number is asserted below */
2211
2212   FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8 == sizeof(buffer));
2213
2214   if(read_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
2215      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2216   entry->length = unpack_uint32_little_endian_(buffer, entry_length_len);
2217
2218   if(0 != entry->entry)
2219      free(entry->entry);
2220
2221   if(entry->length == 0) {
2222      entry->entry = 0;
2223   }
2224   else {
2225      if(0 == (entry->entry = (FLAC__byte*)safe_malloc_add_2op_(entry->length, /*+*/1)))
2226         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2227
2228      if(read_cb(entry->entry, 1, entry->length, handle) != entry->length)
2229         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2230
2231      entry->entry[entry->length] = '\0';
2232   }
2233
2234   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2235}
2236
2237FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment *block)
2238{
2239   unsigned i;
2240   FLAC__Metadata_SimpleIteratorStatus status;
2241   const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
2242   FLAC__byte buffer[4]; /* magic number is asserted below */
2243
2244   FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8 == sizeof(buffer));
2245
2246   if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, &(block->vendor_string))))
2247      return status;
2248
2249   if(read_cb(buffer, 1, num_comments_len, handle) != num_comments_len)
2250      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2251   block->num_comments = unpack_uint32_little_endian_(buffer, num_comments_len);
2252
2253   if(block->num_comments == 0) {
2254      block->comments = 0;
2255   }
2256   else if(0 == (block->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)calloc(block->num_comments, sizeof(FLAC__StreamMetadata_VorbisComment_Entry))))
2257      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2258
2259   for(i = 0; i < block->num_comments; i++) {
2260      if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, block->comments + i)))
2261         return status;
2262   }
2263
2264   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2265}
2266
2267FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track)
2268{
2269   unsigned i, len;
2270   FLAC__byte buffer[32]; /* asserted below that this is big enough */
2271
2272   FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64));
2273   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8);
2274   FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8);
2275
2276   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0);
2277   len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8;
2278   if(read_cb(buffer, 1, len, handle) != len)
2279      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2280   track->offset = unpack_uint64_(buffer, len);
2281
2282   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0);
2283   len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8;
2284   if(read_cb(buffer, 1, len, handle) != len)
2285      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2286   track->number = (FLAC__byte)unpack_uint32_(buffer, len);
2287
2288   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
2289   len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8;
2290   if(read_cb(track->isrc, 1, len, handle) != len)
2291      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2292
2293   FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0);
2294   len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8;
2295   if(read_cb(buffer, 1, len, handle) != len)
2296      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2297   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN == 1);
2298   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN == 1);
2299   track->type = buffer[0] >> 7;
2300   track->pre_emphasis = (buffer[0] >> 6) & 1;
2301
2302   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0);
2303   len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8;
2304   if(read_cb(buffer, 1, len, handle) != len)
2305      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2306   track->num_indices = (FLAC__byte)unpack_uint32_(buffer, len);
2307
2308   if(track->num_indices == 0) {
2309      track->indices = 0;
2310   }
2311   else if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index))))
2312      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2313
2314   for(i = 0; i < track->num_indices; i++) {
2315      FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0);
2316      len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8;
2317      if(read_cb(buffer, 1, len, handle) != len)
2318         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2319      track->indices[i].offset = unpack_uint64_(buffer, len);
2320
2321      FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0);
2322      len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8;
2323      if(read_cb(buffer, 1, len, handle) != len)
2324         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2325      track->indices[i].number = (FLAC__byte)unpack_uint32_(buffer, len);
2326
2327      FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0);
2328      len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8;
2329      if(read_cb(buffer, 1, len, handle) != len)
2330         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2331   }
2332
2333   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2334}
2335
2336FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block)
2337{
2338   unsigned i, len;
2339   FLAC__Metadata_SimpleIteratorStatus status;
2340   FLAC__byte buffer[1024]; /* MSVC needs a constant expression so we put a magic number and assert */
2341
2342   FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN)/8 <= sizeof(buffer));
2343   FLAC__ASSERT(sizeof(FLAC__uint64) <= sizeof(buffer));
2344
2345   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
2346   len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8;
2347   if(read_cb(block->media_catalog_number, 1, len, handle) != len)
2348      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2349
2350   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0);
2351   len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8;
2352   if(read_cb(buffer, 1, len, handle) != len)
2353      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2354   block->lead_in = unpack_uint64_(buffer, len);
2355
2356   FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0);
2357   len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8;
2358   if(read_cb(buffer, 1, len, handle) != len)
2359      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2360   block->is_cd = buffer[0]&0x80? true : false;
2361
2362   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0);
2363   len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8;
2364   if(read_cb(buffer, 1, len, handle) != len)
2365      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2366   block->num_tracks = unpack_uint32_(buffer, len);
2367
2368   if(block->num_tracks == 0) {
2369      block->tracks = 0;
2370   }
2371   else if(0 == (block->tracks = (FLAC__StreamMetadata_CueSheet_Track*)calloc(block->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track))))
2372      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2373
2374   for(i = 0; i < block->num_tracks; i++) {
2375      if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_cuesheet_track_cb_(handle, read_cb, block->tracks + i)))
2376         return status;
2377   }
2378
2379   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2380}
2381
2382static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cstring_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__byte **data, FLAC__uint32 *length, FLAC__uint32 length_len)
2383{
2384   FLAC__byte buffer[sizeof(FLAC__uint32)];
2385
2386   FLAC__ASSERT(0 != data);
2387   FLAC__ASSERT(length_len%8 == 0);
2388
2389   length_len /= 8; /* convert to bytes */
2390
2391   FLAC__ASSERT(sizeof(buffer) >= length_len);
2392
2393   if(read_cb(buffer, 1, length_len, handle) != length_len)
2394      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2395   *length = unpack_uint32_(buffer, length_len);
2396
2397   if(0 != *data)
2398      free(*data);
2399
2400   if(0 == (*data = (FLAC__byte*)safe_malloc_add_2op_(*length, /*+*/1)))
2401      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2402
2403   if(*length > 0) {
2404      if(read_cb(*data, 1, *length, handle) != *length)
2405         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2406   }
2407
2408   (*data)[*length] = '\0';
2409
2410   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2411}
2412
2413FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block)
2414{
2415   FLAC__Metadata_SimpleIteratorStatus status;
2416   FLAC__byte buffer[4]; /* asserted below that this is big enough */
2417   FLAC__uint32 len;
2418
2419   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8);
2420   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8);
2421   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8);
2422   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8);
2423   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8);
2424
2425   FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_TYPE_LEN % 8 == 0);
2426   len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN / 8;
2427   if(read_cb(buffer, 1, len, handle) != len)
2428      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2429   block->type = /*(FLAC__StreamMetadata_Picture_Type)*/unpack_uint32_(buffer, len); // changed for MAME, check
2430
2431   if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, (FLAC__byte**)(&(block->mime_type)), &len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
2432      return status;
2433
2434   if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->description), &len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
2435      return status;
2436
2437   FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN % 8 == 0);
2438   len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN / 8;
2439   if(read_cb(buffer, 1, len, handle) != len)
2440      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2441   block->width = unpack_uint32_(buffer, len);
2442
2443   FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN % 8 == 0);
2444   len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN / 8;
2445   if(read_cb(buffer, 1, len, handle) != len)
2446      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2447   block->height = unpack_uint32_(buffer, len);
2448
2449   FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN % 8 == 0);
2450   len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN / 8;
2451   if(read_cb(buffer, 1, len, handle) != len)
2452      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2453   block->depth = unpack_uint32_(buffer, len);
2454
2455   FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_COLORS_LEN % 8 == 0);
2456   len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN / 8;
2457   if(read_cb(buffer, 1, len, handle) != len)
2458      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2459   block->colors = unpack_uint32_(buffer, len);
2460
2461   /* for convenience we use read_metadata_block_data_picture_cstring_cb_() even though it adds an extra terminating NUL we don't use */
2462   if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->data), &(block->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
2463      return status;
2464
2465   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2466}
2467
2468FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length)
2469{
2470   if(block_length == 0) {
2471      block->data = 0;
2472   }
2473   else {
2474      if(0 == (block->data = (FLAC__byte*)malloc(block_length)))
2475         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2476
2477      if(read_cb(block->data, 1, block_length, handle) != block_length)
2478         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2479   }
2480
2481   return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2482}
2483
2484FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
2485{
2486   FLAC__ASSERT(0 != file);
2487   FLAC__ASSERT(0 != status);
2488
2489   if(!write_metadata_block_header_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) {
2490      *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2491      return false;
2492   }
2493
2494   return true;
2495}
2496
2497FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
2498{
2499   FLAC__ASSERT(0 != file);
2500   FLAC__ASSERT(0 != status);
2501
2502   if (write_metadata_block_data_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) {
2503      *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2504      return true;
2505   }
2506   else {
2507      *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2508      return false;
2509   }
2510}
2511
2512FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block)
2513{
2514   FLAC__byte buffer[FLAC__STREAM_METADATA_HEADER_LENGTH];
2515
2516   FLAC__ASSERT(block->length < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
2517
2518   buffer[0] = (block->is_last? 0x80 : 0) | (FLAC__byte)block->type;
2519   pack_uint32_(block->length, buffer + 1, 3);
2520
2521   if(write_cb(buffer, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH)
2522      return false;
2523
2524   return true;
2525}
2526
2527FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block)
2528{
2529   FLAC__ASSERT(0 != block);
2530
2531   switch(block->type) {
2532      case FLAC__METADATA_TYPE_STREAMINFO:
2533         return write_metadata_block_data_streaminfo_cb_(handle, write_cb, &block->data.stream_info);
2534      case FLAC__METADATA_TYPE_PADDING:
2535         return write_metadata_block_data_padding_cb_(handle, write_cb, &block->data.padding, block->length);
2536      case FLAC__METADATA_TYPE_APPLICATION:
2537         return write_metadata_block_data_application_cb_(handle, write_cb, &block->data.application, block->length);
2538      case FLAC__METADATA_TYPE_SEEKTABLE:
2539         return write_metadata_block_data_seektable_cb_(handle, write_cb, &block->data.seek_table);
2540      case FLAC__METADATA_TYPE_VORBIS_COMMENT:
2541         return write_metadata_block_data_vorbis_comment_cb_(handle, write_cb, &block->data.vorbis_comment);
2542      case FLAC__METADATA_TYPE_CUESHEET:
2543         return write_metadata_block_data_cuesheet_cb_(handle, write_cb, &block->data.cue_sheet);
2544      case FLAC__METADATA_TYPE_PICTURE:
2545         return write_metadata_block_data_picture_cb_(handle, write_cb, &block->data.picture);
2546      default:
2547         return write_metadata_block_data_unknown_cb_(handle, write_cb, &block->data.unknown, block->length);
2548   }
2549}
2550
2551FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block)
2552{
2553   FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
2554   const unsigned channels1 = block->channels - 1;
2555   const unsigned bps1 = block->bits_per_sample - 1;
2556
2557   /* we are using hardcoded numbers for simplicity but we should
2558    * probably eventually write a bit-level packer and use the
2559    * _STREAMINFO_ constants.
2560    */
2561   pack_uint32_(block->min_blocksize, buffer, 2);
2562   pack_uint32_(block->max_blocksize, buffer+2, 2);
2563   pack_uint32_(block->min_framesize, buffer+4, 3);
2564   pack_uint32_(block->max_framesize, buffer+7, 3);
2565   buffer[10] = (block->sample_rate >> 12) & 0xff;
2566   buffer[11] = (block->sample_rate >> 4) & 0xff;
2567   buffer[12] = ((block->sample_rate & 0x0f) << 4) | (channels1 << 1) | (bps1 >> 4);
2568   buffer[13] = (FLAC__byte)(((bps1 & 0x0f) << 4) | ((block->total_samples >> 32) & 0x0f));
2569   pack_uint32_((FLAC__uint32)block->total_samples, buffer+14, 4);
2570   memcpy(buffer+18, block->md5sum, 16);
2571
2572   if(write_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
2573      return false;
2574
2575   return true;
2576}
2577
2578FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length)
2579{
2580   unsigned i, n = block_length;
2581   FLAC__byte buffer[1024];
2582
2583   (void)block;
2584
2585   memset(buffer, 0, 1024);
2586
2587   for(i = 0; i < n/1024; i++)
2588      if(write_cb(buffer, 1, 1024, handle) != 1024)
2589         return false;
2590
2591   n %= 1024;
2592
2593   if(write_cb(buffer, 1, n, handle) != n)
2594      return false;
2595
2596   return true;
2597}
2598
2599FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length)
2600{
2601   const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
2602
2603   if(write_cb(block->id, 1, id_bytes, handle) != id_bytes)
2604      return false;
2605
2606   block_length -= id_bytes;
2607
2608   if(write_cb(block->data, 1, block_length, handle) != block_length)
2609      return false;
2610
2611   return true;
2612}
2613
2614FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block)
2615{
2616   unsigned i;
2617   FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
2618
2619   for(i = 0; i < block->num_points; i++) {
2620      /* some MAGIC NUMBERs here */
2621      pack_uint64_(block->points[i].sample_number, buffer, 8);
2622      pack_uint64_(block->points[i].stream_offset, buffer+8, 8);
2623      pack_uint32_(block->points[i].frame_samples, buffer+16, 2);
2624      if(write_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
2625         return false;
2626   }
2627
2628   return true;
2629}
2630
2631FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block)
2632{
2633   unsigned i;
2634   const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
2635   const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
2636   FLAC__byte buffer[4]; /* magic number is asserted below */
2637
2638   FLAC__ASSERT(max(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN, FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8 == sizeof(buffer));
2639
2640   pack_uint32_little_endian_(block->vendor_string.length, buffer, entry_length_len);
2641   if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
2642      return false;
2643   if(write_cb(block->vendor_string.entry, 1, block->vendor_string.length, handle) != block->vendor_string.length)
2644      return false;
2645
2646   pack_uint32_little_endian_(block->num_comments, buffer, num_comments_len);
2647   if(write_cb(buffer, 1, num_comments_len, handle) != num_comments_len)
2648      return false;
2649
2650   for(i = 0; i < block->num_comments; i++) {
2651      pack_uint32_little_endian_(block->comments[i].length, buffer, entry_length_len);
2652      if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
2653         return false;
2654      if(write_cb(block->comments[i].entry, 1, block->comments[i].length, handle) != block->comments[i].length)
2655         return false;
2656   }
2657
2658   return true;
2659}
2660
2661FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block)
2662{
2663   unsigned i, j, len;
2664   FLAC__byte buffer[1024]; /* asserted below that this is big enough */
2665
2666   FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64));
2667   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN/8);
2668   FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN)/8);
2669   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8);
2670
2671   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
2672   len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8;
2673   if(write_cb(block->media_catalog_number, 1, len, handle) != len)
2674      return false;
2675
2676   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0);
2677   len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8;
2678   pack_uint64_(block->lead_in, buffer, len);
2679   if(write_cb(buffer, 1, len, handle) != len)
2680      return false;
2681
2682   FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0);
2683   len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8;
2684   memset(buffer, 0, len);
2685   if(block->is_cd)
2686      buffer[0] |= 0x80;
2687   if(write_cb(buffer, 1, len, handle) != len)
2688      return false;
2689
2690   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0);
2691   len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8;
2692   pack_uint32_(block->num_tracks, buffer, len);
2693   if(write_cb(buffer, 1, len, handle) != len)
2694      return false;
2695
2696   for(i = 0; i < block->num_tracks; i++) {
2697      FLAC__StreamMetadata_CueSheet_Track *track = block->tracks + i;
2698
2699      FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0);
2700      len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8;
2701      pack_uint64_(track->offset, buffer, len);
2702      if(write_cb(buffer, 1, len, handle) != len)
2703         return false;
2704
2705      FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0);
2706      len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8;
2707      pack_uint32_(track->number, buffer, len);
2708      if(write_cb(buffer, 1, len, handle) != len)
2709         return false;
2710
2711      FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
2712      len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8;
2713      if(write_cb(track->isrc, 1, len, handle) != len)
2714         return false;
2715
2716      FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0);
2717      len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8;
2718      memset(buffer, 0, len);
2719      buffer[0] = (track->type << 7) | (track->pre_emphasis << 6);
2720      if(write_cb(buffer, 1, len, handle) != len)
2721         return false;
2722
2723      FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0);
2724      len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8;
2725      pack_uint32_(track->num_indices, buffer, len);
2726      if(write_cb(buffer, 1, len, handle) != len)
2727         return false;
2728
2729      for(j = 0; j < track->num_indices; j++) {
2730         FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
2731
2732         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0);
2733         len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8;
2734         pack_uint64_(index->offset, buffer, len);
2735         if(write_cb(buffer, 1, len, handle) != len)
2736            return false;
2737
2738         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0);
2739         len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8;
2740         pack_uint32_(index->number, buffer, len);
2741         if(write_cb(buffer, 1, len, handle) != len)
2742            return false;
2743
2744         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0);
2745         len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8;
2746         memset(buffer, 0, len);
2747         if(write_cb(buffer, 1, len, handle) != len)
2748            return false;
2749      }
2750   }
2751
2752   return true;
2753}
2754
2755FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block)
2756{
2757   unsigned len;
2758   size_t slen;
2759   FLAC__byte buffer[4]; /* magic number is asserted below */
2760
2761   FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_TYPE_LEN%8);
2762   FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN%8);
2763   FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN%8);
2764   FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN%8);
2765   FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN%8);
2766   FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN%8);
2767   FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_COLORS_LEN%8);
2768   FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN%8);
2769   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8);
2770   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8);
2771   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8);
2772   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8);
2773   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8);
2774   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8);
2775   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8);
2776   FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8);
2777
2778   len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8;
2779   pack_uint32_(block->type, buffer, len);
2780   if(write_cb(buffer, 1, len, handle) != len)
2781      return false;
2782
2783   len = FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8;
2784   slen = strlen(block->mime_type);
2785   pack_uint32_(slen, buffer, len);
2786   if(write_cb(buffer, 1, len, handle) != len)
2787      return false;
2788   if(write_cb(block->mime_type, 1, slen, handle) != slen)
2789      return false;
2790
2791   len = FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8;
2792   slen = strlen((const char *)block->description);
2793   pack_uint32_(slen, buffer, len);
2794   if(write_cb(buffer, 1, len, handle) != len)
2795      return false;
2796   if(write_cb(block->description, 1, slen, handle) != slen)
2797      return false;
2798
2799   len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8;
2800   pack_uint32_(block->width, buffer, len);
2801   if(write_cb(buffer, 1, len, handle) != len)
2802      return false;
2803
2804   len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8;
2805   pack_uint32_(block->height, buffer, len);
2806   if(write_cb(buffer, 1, len, handle) != len)
2807      return false;
2808
2809   len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8;
2810   pack_uint32_(block->depth, buffer, len);
2811   if(write_cb(buffer, 1, len, handle) != len)
2812      return false;
2813
2814   len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8;
2815   pack_uint32_(block->colors, buffer, len);
2816   if(write_cb(buffer, 1, len, handle) != len)
2817      return false;
2818
2819   len = FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8;
2820   pack_uint32_(block->data_length, buffer, len);
2821   if(write_cb(buffer, 1, len, handle) != len)
2822      return false;
2823   if(write_cb(block->data, 1, block->data_length, handle) != block->data_length)
2824      return false;
2825
2826   return true;
2827}
2828
2829FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length)
2830{
2831   if(write_cb(block->data, 1, block_length, handle) != block_length)
2832      return false;
2833
2834   return true;
2835}
2836
2837FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block)
2838{
2839   if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2840      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2841      return false;
2842   }
2843
2844   if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
2845      return false;
2846
2847   if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
2848      return false;
2849
2850   if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2851      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2852      return false;
2853   }
2854
2855   return read_metadata_block_header_(iterator);
2856}
2857
2858FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last)
2859{
2860   FLAC__StreamMetadata *padding;
2861
2862   if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2863      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2864      return false;
2865   }
2866
2867   block->is_last = false;
2868
2869   if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
2870      return false;
2871
2872   if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
2873      return false;
2874
2875   if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)))
2876      return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2877
2878   padding->is_last = padding_is_last;
2879   padding->length = padding_length;
2880
2881   if(!write_metadata_block_header_(iterator->file, &iterator->status, padding)) {
2882      FLAC__metadata_object_delete(padding);
2883      return false;
2884   }
2885
2886   if(!write_metadata_block_data_(iterator->file, &iterator->status, padding)) {
2887      FLAC__metadata_object_delete(padding);
2888      return false;
2889   }
2890
2891   FLAC__metadata_object_delete(padding);
2892
2893   if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2894      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2895      return false;
2896   }
2897
2898   return read_metadata_block_header_(iterator);
2899}
2900
2901FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append)
2902{
2903   FILE *tempfile;
2904   char *tempfilename;
2905   int fixup_is_last_code = 0; /* 0 => no need to change any is_last flags */
2906   off_t fixup_is_last_flag_offset = -1;
2907
2908   FLAC__ASSERT(0 != block || append == false);
2909
2910   if(iterator->is_last) {
2911      if(append) {
2912         fixup_is_last_code = 1; /* 1 => clear the is_last flag at the following offset */
2913         fixup_is_last_flag_offset = iterator->offset[iterator->depth];
2914      }
2915      else if(0 == block) {
2916         simple_iterator_push_(iterator);
2917         if(!FLAC__metadata_simple_iterator_prev(iterator)) {
2918            (void)simple_iterator_pop_(iterator);
2919            return false;
2920         }
2921         fixup_is_last_code = -1; /* -1 => set the is_last the flag at the following offset */
2922         fixup_is_last_flag_offset = iterator->offset[iterator->depth];
2923         if(!simple_iterator_pop_(iterator))
2924            return false;
2925      }
2926   }
2927
2928   if(!simple_iterator_copy_file_prefix_(iterator, &tempfile, &tempfilename, append))
2929      return false;
2930
2931   if(0 != block) {
2932      if(!write_metadata_block_header_(tempfile, &iterator->status, block)) {
2933         cleanup_tempfile_(&tempfile, &tempfilename);
2934         return false;
2935      }
2936
2937      if(!write_metadata_block_data_(tempfile, &iterator->status, block)) {
2938         cleanup_tempfile_(&tempfile, &tempfilename);
2939         return false;
2940      }
2941   }
2942
2943   if(!simple_iterator_copy_file_postfix_(iterator, &tempfile, &tempfilename, fixup_is_last_code, fixup_is_last_flag_offset, block==0))
2944      return false;
2945
2946   if(append)
2947      return FLAC__metadata_simple_iterator_next(iterator);
2948
2949   return true;
2950}
2951
2952void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator)
2953{
2954   FLAC__ASSERT(iterator->depth+1 < SIMPLE_ITERATOR_MAX_PUSH_DEPTH);
2955   iterator->offset[iterator->depth+1] = iterator->offset[iterator->depth];
2956   iterator->depth++;
2957}
2958
2959FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator)
2960{
2961   FLAC__ASSERT(iterator->depth > 0);
2962   iterator->depth--;
2963   if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2964      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2965      return false;
2966   }
2967
2968   return read_metadata_block_header_(iterator);
2969}
2970
2971/* return meanings:
2972 * 0: ok
2973 * 1: read error
2974 * 2: seek error
2975 * 3: not a FLAC file
2976 */
2977unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb)
2978{
2979   FLAC__byte buffer[4];
2980   size_t n;
2981   unsigned i;
2982
2983   FLAC__ASSERT(FLAC__STREAM_SYNC_LENGTH == sizeof(buffer));
2984
2985   /* skip any id3v2 tag */
2986   errno = 0;
2987   n = read_cb(buffer, 1, 4, handle);
2988   if(errno)
2989      return 1;
2990   else if(n != 4)
2991      return 3;
2992   else if(0 == memcmp(buffer, "ID3", 3)) {
2993      unsigned tag_length = 0;
2994
2995      /* skip to the tag length */
2996      if(seek_cb(handle, 2, SEEK_CUR) < 0)
2997         return 2;
2998
2999      /* read the length */
3000      for(i = 0; i < 4; i++) {
3001         if(read_cb(buffer, 1, 1, handle) < 1 || buffer[0] & 0x80)
3002            return 1;
3003         tag_length <<= 7;
3004         tag_length |= (buffer[0] & 0x7f);
3005      }
3006
3007      /* skip the rest of the tag */
3008      if(seek_cb(handle, tag_length, SEEK_CUR) < 0)
3009         return 2;
3010
3011      /* read the stream sync code */
3012      errno = 0;
3013      n = read_cb(buffer, 1, 4, handle);
3014      if(errno)
3015         return 1;
3016      else if(n != 4)
3017         return 3;
3018   }
3019
3020   /* check for the fLaC signature */
3021   if(0 == memcmp(FLAC__STREAM_SYNC_STRING, buffer, FLAC__STREAM_SYNC_LENGTH))
3022      return 0;
3023   else
3024      return 3;
3025}
3026
3027unsigned seek_to_first_metadata_block_(FILE *f)
3028{
3029   return seek_to_first_metadata_block_cb_((FLAC__IOHandle)f, (FLAC__IOCallback_Read)fread, fseek_wrapper_);
3030}
3031
3032FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append)
3033{
3034   const off_t offset_end = append? iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length : iterator->offset[iterator->depth];
3035
3036   if(0 != fseeko(iterator->file, 0, SEEK_SET)) {
3037      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3038      return false;
3039   }
3040   if(!open_tempfile_(iterator->filename, iterator->tempfile_path_prefix, tempfile, tempfilename, &iterator->status)) {
3041      cleanup_tempfile_(tempfile, tempfilename);
3042      return false;
3043   }
3044   if(!copy_n_bytes_from_file_(iterator->file, *tempfile, offset_end, &iterator->status)) {
3045      cleanup_tempfile_(tempfile, tempfilename);
3046      return false;
3047   }
3048
3049   return true;
3050}
3051
3052FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, off_t fixup_is_last_flag_offset, FLAC__bool backup)
3053{
3054   off_t save_offset = iterator->offset[iterator->depth];
3055   FLAC__ASSERT(0 != *tempfile);
3056
3057   if(0 != fseeko(iterator->file, save_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length, SEEK_SET)) {
3058      cleanup_tempfile_(tempfile, tempfilename);
3059      iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3060      return false;
3061   }
3062   if(!copy_remaining_bytes_from_file_(iterator->file, *tempfile, &iterator->status)) {
3063      cleanup_tempfile_(tempfile, tempfilename);
3064      return false;
3065   }
3066
3067   if(fixup_is_last_code != 0) {
3068      /*
3069       * if code == 1, it means a block was appended to the end so
3070       *   we have to clear the is_last flag of the previous block
3071       * if code == -1, it means the last block was deleted so
3072       *   we have to set the is_last flag of the previous block
3073       */
3074      /* MAGIC NUMBERs here; we know the is_last flag is the high bit of the byte at this location */
3075      FLAC__byte x;
3076      if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
3077         cleanup_tempfile_(tempfile, tempfilename);
3078         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3079         return false;
3080      }
3081      if(fread(&x, 1, 1, *tempfile) != 1) {
3082         cleanup_tempfile_(tempfile, tempfilename);
3083         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3084         return false;
3085      }
3086      if(fixup_is_last_code > 0) {
3087         FLAC__ASSERT(x & 0x80);
3088         x &= 0x7f;
3089      }
3090      else {
3091         FLAC__ASSERT(!(x & 0x80));
3092         x |= 0x80;
3093      }
3094      if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
3095         cleanup_tempfile_(tempfile, tempfilename);
3096         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3097         return false;
3098      }
3099      if(local__fwrite(&x, 1, 1, *tempfile) != 1) {
3100         cleanup_tempfile_(tempfile, tempfilename);
3101         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3102         return false;
3103      }
3104   }
3105
3106   (void)fclose(iterator->file);
3107
3108   if(!transport_tempfile_(iterator->filename, tempfile, tempfilename, &iterator->status))
3109      return false;
3110
3111   if(iterator->has_stats)
3112      set_file_stats_(iterator->filename, &iterator->stats);
3113
3114   if(!simple_iterator_prime_input_(iterator, !iterator->is_writable))
3115      return false;
3116   if(backup) {
3117      while(iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length < save_offset)
3118         if(!FLAC__metadata_simple_iterator_next(iterator))
3119            return false;
3120      return true;
3121   }
3122   else {
3123      /* move the iterator to it's original block faster by faking a push, then doing a pop_ */
3124      FLAC__ASSERT(iterator->depth == 0);
3125      iterator->offset[0] = save_offset;
3126      iterator->depth++;
3127      return simple_iterator_pop_(iterator);
3128   }
3129}
3130
3131FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status)
3132{
3133   FLAC__byte buffer[8192];
3134   size_t n;
3135
3136   FLAC__ASSERT(bytes >= 0);
3137   while(bytes > 0) {
3138      n = min(sizeof(buffer), (size_t)bytes);
3139      if(fread(buffer, 1, n, file) != n) {
3140         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3141         return false;
3142      }
3143      if(local__fwrite(buffer, 1, n, tempfile) != n) {
3144         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3145         return false;
3146      }
3147      bytes -= n;
3148   }
3149
3150   return true;
3151}
3152
3153FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status)
3154{
3155   FLAC__byte buffer[8192];
3156   size_t n;
3157
3158   FLAC__ASSERT(bytes >= 0);
3159   while(bytes > 0) {
3160      n = min(sizeof(buffer), (size_t)bytes);
3161      if(read_cb(buffer, 1, n, handle) != n) {
3162         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3163         return false;
3164      }
3165      if(temp_write_cb(buffer, 1, n, temp_handle) != n) {
3166         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3167         return false;
3168      }
3169      bytes -= n;
3170   }
3171
3172   return true;
3173}
3174
3175FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status)
3176{
3177   FLAC__byte buffer[8192];
3178   size_t n;
3179
3180   while(!feof(file)) {
3181      n = fread(buffer, 1, sizeof(buffer), file);
3182      if(n == 0 && !feof(file)) {
3183         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3184         return false;
3185      }
3186      if(n > 0 && local__fwrite(buffer, 1, n, tempfile) != n) {
3187         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3188         return false;
3189      }
3190   }
3191
3192   return true;
3193}
3194
3195FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status)
3196{
3197   FLAC__byte buffer[8192];
3198   size_t n;
3199
3200   while(!eof_cb(handle)) {
3201      n = read_cb(buffer, 1, sizeof(buffer), handle);
3202      if(n == 0 && !eof_cb(handle)) {
3203         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3204         return false;
3205      }
3206      if(n > 0 && temp_write_cb(buffer, 1, n, temp_handle) != n) {
3207         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3208         return false;
3209      }
3210   }
3211
3212   return true;
3213}
3214
3215FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
3216{
3217   static const char *tempfile_suffix = ".metadata_edit";
3218   if(0 == tempfile_path_prefix) {
3219      if(0 == (*tempfilename = (char*)safe_malloc_add_3op_(strlen(filename), /*+*/strlen(tempfile_suffix), /*+*/1))) {
3220         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
3221         return false;
3222      }
3223      strcpy(*tempfilename, filename);
3224      strcat(*tempfilename, tempfile_suffix);
3225   }
3226   else {
3227      const char *p = strrchr(filename, '/');
3228      if(0 == p)
3229         p = filename;
3230      else
3231         p++;
3232
3233      if(0 == (*tempfilename = (char*)safe_malloc_add_4op_(strlen(tempfile_path_prefix), /*+*/strlen(p), /*+*/strlen(tempfile_suffix), /*+*/2))) {
3234         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
3235         return false;
3236      }
3237      strcpy(*tempfilename, tempfile_path_prefix);
3238      strcat(*tempfilename, "/");
3239      strcat(*tempfilename, p);
3240      strcat(*tempfilename, tempfile_suffix);
3241   }
3242
3243   if(0 == (*tempfile = fopen(*tempfilename, "w+b"))) {
3244      *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
3245      return false;
3246   }
3247
3248   return true;
3249}
3250
3251FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
3252{
3253   FLAC__ASSERT(0 != filename);
3254   FLAC__ASSERT(0 != tempfile);
3255   FLAC__ASSERT(0 != *tempfile);
3256   FLAC__ASSERT(0 != tempfilename);
3257   FLAC__ASSERT(0 != *tempfilename);
3258   FLAC__ASSERT(0 != status);
3259
3260   (void)fclose(*tempfile);
3261   *tempfile = 0;
3262
3263#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ || defined __EMX__
3264   /* on some flavors of windows, rename() will fail if the destination already exists */
3265   if(unlink(filename) < 0) {
3266      cleanup_tempfile_(tempfile, tempfilename);
3267      *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR;
3268      return false;
3269   }
3270#endif
3271
3272   /*@@@ to fully support the tempfile_path_prefix we need to update this piece to actually copy across filesystems instead of just rename(): */
3273   if(0 != rename(*tempfilename, filename)) {
3274      cleanup_tempfile_(tempfile, tempfilename);
3275      *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR;
3276      return false;
3277   }
3278
3279   cleanup_tempfile_(tempfile, tempfilename);
3280
3281   return true;
3282}
3283
3284void cleanup_tempfile_(FILE **tempfile, char **tempfilename)
3285{
3286   if(0 != *tempfile) {
3287      (void)fclose(*tempfile);
3288      *tempfile = 0;
3289   }
3290
3291   if(0 != *tempfilename) {
3292      (void)unlink(*tempfilename);
3293      free(*tempfilename);
3294      *tempfilename = 0;
3295   }
3296}
3297
3298FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
3299{
3300   FLAC__ASSERT(0 != filename);
3301   FLAC__ASSERT(0 != stats);
3302   return (0 == stat(filename, stats));
3303}
3304
3305void set_file_stats_(const char *filename, struct stat *stats)
3306{
3307   struct utimbuf srctime;
3308
3309   FLAC__ASSERT(0 != filename);
3310   FLAC__ASSERT(0 != stats);
3311
3312   srctime.actime = stats->st_atime;
3313   srctime.modtime = stats->st_mtime;
3314   (void)chmod(filename, stats->st_mode);
3315   (void)utime(filename, &srctime);
3316#if !defined _MSC_VER && !defined __BORLANDC__ && !defined __MINGW32__ && !defined __EMX__
3317   (void)chown(filename, stats->st_uid, -1);
3318   (void)chown(filename, -1, stats->st_gid);
3319#endif
3320}
3321
3322int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence)
3323{
3324   return fseeko((FILE*)handle, (off_t)offset, whence);
3325}
3326
3327FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle)
3328{
3329   return ftello((FILE*)handle);
3330}
3331
3332FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status)
3333{
3334   switch(status) {
3335      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK:
3336         return FLAC__METADATA_CHAIN_STATUS_OK;
3337      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT:
3338         return FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT;
3339      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE:
3340         return FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
3341      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE:
3342         return FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
3343      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE:
3344         return FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE;
3345      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA:
3346         return FLAC__METADATA_CHAIN_STATUS_BAD_METADATA;
3347      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR:
3348         return FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
3349      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR:
3350         return FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
3351      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR:
3352         return FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
3353      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR:
3354         return FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR;
3355      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR:
3356         return FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR;
3357      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR:
3358         return FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
3359      case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR:
3360      default:
3361         return FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
3362   }
3363}
src/lib/libflac/libflac/lpc.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include <math.h>
37#include "flac/assert.h"
38#include "flac/format.h"
39#include "private/bitmath.h"
40#include "private/lpc.h"
41#if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
42#include <stdio.h>
43#endif
44
45#ifndef FLAC__INTEGER_ONLY_LIBRARY
46
47#ifndef M_LN2
48/* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
49#define M_LN2 0.69314718055994530942
50#endif
51
52/* OPT: #undef'ing this may improve the speed on some architectures */
53#define FLAC__LPC_UNROLLED_FILTER_LOOPS
54
55
56void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
57{
58   unsigned i;
59   for(i = 0; i < data_len; i++)
60      out[i] = in[i] * window[i];
61}
62
63void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
64{
65   /* a readable, but slower, version */
66#if 0
67   FLAC__real d;
68   unsigned i;
69
70   FLAC__ASSERT(lag > 0);
71   FLAC__ASSERT(lag <= data_len);
72
73   /*
74    * Technically we should subtract the mean first like so:
75    *   for(i = 0; i < data_len; i++)
76    *     data[i] -= mean;
77    * but it appears not to make enough of a difference to matter, and
78    * most signals are already closely centered around zero
79    */
80   while(lag--) {
81      for(i = lag, d = 0.0; i < data_len; i++)
82         d += data[i] * data[i - lag];
83      autoc[lag] = d;
84   }
85#endif
86
87   /*
88    * this version tends to run faster because of better data locality
89    * ('data_len' is usually much larger than 'lag')
90    */
91   FLAC__real d;
92   unsigned sample, coeff;
93   const unsigned limit = data_len - lag;
94
95   FLAC__ASSERT(lag > 0);
96   FLAC__ASSERT(lag <= data_len);
97
98   for(coeff = 0; coeff < lag; coeff++)
99      autoc[coeff] = 0.0;
100   for(sample = 0; sample <= limit; sample++) {
101      d = data[sample];
102      for(coeff = 0; coeff < lag; coeff++)
103         autoc[coeff] += d * data[sample+coeff];
104   }
105   for(; sample < data_len; sample++) {
106      d = data[sample];
107      for(coeff = 0; coeff < data_len - sample; coeff++)
108         autoc[coeff] += d * data[sample+coeff];
109   }
110}
111
112void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
113{
114   unsigned i, j;
115   FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
116
117   FLAC__ASSERT(0 != max_order);
118   FLAC__ASSERT(0 < *max_order);
119   FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
120   FLAC__ASSERT(autoc[0] != 0.0);
121
122   err = autoc[0];
123
124   for(i = 0; i < *max_order; i++) {
125      /* Sum up this iteration's reflection coefficient. */
126      r = -autoc[i+1];
127      for(j = 0; j < i; j++)
128         r -= lpc[j] * autoc[i-j];
129      ref[i] = (r/=err);
130
131      /* Update LPC coefficients and total error. */
132      lpc[i]=r;
133      for(j = 0; j < (i>>1); j++) {
134         FLAC__double tmp = lpc[j];
135         lpc[j] += r * lpc[i-1-j];
136         lpc[i-1-j] += r * tmp;
137      }
138      if(i & 1)
139         lpc[j] += lpc[j] * r;
140
141      err *= (1.0 - r * r);
142
143      /* save this order */
144      for(j = 0; j <= i; j++)
145         lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
146      error[i] = err;
147
148      /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
149      if(err == 0.0) {
150         *max_order = i+1;
151         return;
152      }
153   }
154}
155
156int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
157{
158   unsigned i;
159   FLAC__double cmax;
160   FLAC__int32 qmax, qmin;
161
162   FLAC__ASSERT(precision > 0);
163   FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
164
165   /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
166   precision--;
167   qmax = 1 << precision;
168   qmin = -qmax;
169   qmax--;
170
171   /* calc cmax = max( |lp_coeff[i]| ) */
172   cmax = 0.0;
173   for(i = 0; i < order; i++) {
174      const FLAC__double d = fabs(lp_coeff[i]);
175      if(d > cmax)
176         cmax = d;
177   }
178
179   if(cmax <= 0.0) {
180      /* => coefficients are all 0, which means our constant-detect didn't work */
181      return 2;
182   }
183   else {
184      const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
185      const int min_shiftlimit = -max_shiftlimit - 1;
186      int log2cmax;
187
188      (void)frexp(cmax, &log2cmax);
189      log2cmax--;
190      *shift = (int)precision - log2cmax - 1;
191
192      if(*shift > max_shiftlimit)
193         *shift = max_shiftlimit;
194      else if(*shift < min_shiftlimit)
195         return 1;
196   }
197
198   if(*shift >= 0) {
199      FLAC__double error = 0.0;
200      FLAC__int32 q;
201      for(i = 0; i < order; i++) {
202         error += lp_coeff[i] * (1 << *shift);
203#if 1 /* unfortunately lround() is C99 */
204         if(error >= 0.0)
205            q = (FLAC__int32)(error + 0.5);
206         else
207            q = (FLAC__int32)(error - 0.5);
208#else
209         q = lround(error);
210#endif
211#ifdef FLAC__OVERFLOW_DETECT
212         if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
213            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]);
214         else if(q < qmin)
215            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]);
216#endif
217         if(q > qmax)
218            q = qmax;
219         else if(q < qmin)
220            q = qmin;
221         error -= q;
222         qlp_coeff[i] = q;
223      }
224   }
225   /* negative shift is very rare but due to design flaw, negative shift is
226    * a NOP in the decoder, so it must be handled specially by scaling down
227    * coeffs
228    */
229   else {
230      const int nshift = -(*shift);
231      FLAC__double error = 0.0;
232      FLAC__int32 q;
233#ifdef DEBUG
234      fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
235#endif
236      for(i = 0; i < order; i++) {
237         error += lp_coeff[i] / (1 << nshift);
238#if 1 /* unfortunately lround() is C99 */
239         if(error >= 0.0)
240            q = (FLAC__int32)(error + 0.5);
241         else
242            q = (FLAC__int32)(error - 0.5);
243#else
244         q = lround(error);
245#endif
246#ifdef FLAC__OVERFLOW_DETECT
247         if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
248            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]);
249         else if(q < qmin)
250            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]);
251#endif
252         if(q > qmax)
253            q = qmax;
254         else if(q < qmin)
255            q = qmin;
256         error -= q;
257         qlp_coeff[i] = q;
258      }
259      *shift = 0;
260   }
261
262   return 0;
263}
264
265void 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[])
266#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
267{
268   FLAC__int64 sumo;
269   unsigned i, j;
270   FLAC__int32 sum;
271   const FLAC__int32 *history;
272
273#ifdef FLAC__OVERFLOW_DETECT_VERBOSE
274   fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
275   for(i=0;i<order;i++)
276      fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
277   fprintf(stderr,"\n");
278#endif
279   FLAC__ASSERT(order > 0);
280
281   for(i = 0; i < data_len; i++) {
282      sumo = 0;
283      sum = 0;
284      history = data;
285      for(j = 0; j < order; j++) {
286         sum += qlp_coeff[j] * (*(--history));
287         sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
288#if defined _MSC_VER
289         if(sumo > 2147483647I64 || sumo < -2147483648I64)
290            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);
291#else
292         if(sumo > 2147483647ll || sumo < -2147483648ll)
293            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);
294#endif
295      }
296      *(residual++) = *(data++) - (sum >> lp_quantization);
297   }
298
299   /* Here's a slower but clearer version:
300   for(i = 0; i < data_len; i++) {
301      sum = 0;
302      for(j = 0; j < order; j++)
303         sum += qlp_coeff[j] * data[i-j-1];
304      residual[i] = data[i] - (sum >> lp_quantization);
305   }
306   */
307}
308#else /* fully unrolled version for normal use */
309{
310   int i;
311   FLAC__int32 sum;
312
313   FLAC__ASSERT(order > 0);
314   FLAC__ASSERT(order <= 32);
315
316   /*
317    * We do unique versions up to 12th order since that's the subset limit.
318    * Also they are roughly ordered to match frequency of occurrence to
319    * minimize branching.
320    */
321   if(order <= 12) {
322      if(order > 8) {
323         if(order > 10) {
324            if(order == 12) {
325               for(i = 0; i < (int)data_len; i++) {
326                  sum = 0;
327                  sum += qlp_coeff[11] * data[i-12];
328                  sum += qlp_coeff[10] * data[i-11];
329                  sum += qlp_coeff[9] * data[i-10];
330                  sum += qlp_coeff[8] * data[i-9];
331                  sum += qlp_coeff[7] * data[i-8];
332                  sum += qlp_coeff[6] * data[i-7];
333                  sum += qlp_coeff[5] * data[i-6];
334                  sum += qlp_coeff[4] * data[i-5];
335                  sum += qlp_coeff[3] * data[i-4];
336                  sum += qlp_coeff[2] * data[i-3];
337                  sum += qlp_coeff[1] * data[i-2];
338                  sum += qlp_coeff[0] * data[i-1];
339                  residual[i] = data[i] - (sum >> lp_quantization);
340               }
341            }
342            else { /* order == 11 */
343               for(i = 0; i < (int)data_len; i++) {
344                  sum = 0;
345                  sum += qlp_coeff[10] * data[i-11];
346                  sum += qlp_coeff[9] * data[i-10];
347                  sum += qlp_coeff[8] * data[i-9];
348                  sum += qlp_coeff[7] * data[i-8];
349                  sum += qlp_coeff[6] * data[i-7];
350                  sum += qlp_coeff[5] * data[i-6];
351                  sum += qlp_coeff[4] * data[i-5];
352                  sum += qlp_coeff[3] * data[i-4];
353                  sum += qlp_coeff[2] * data[i-3];
354                  sum += qlp_coeff[1] * data[i-2];
355                  sum += qlp_coeff[0] * data[i-1];
356                  residual[i] = data[i] - (sum >> lp_quantization);
357               }
358            }
359         }
360         else {
361            if(order == 10) {
362               for(i = 0; i < (int)data_len; i++) {
363                  sum = 0;
364                  sum += qlp_coeff[9] * data[i-10];
365                  sum += qlp_coeff[8] * data[i-9];
366                  sum += qlp_coeff[7] * data[i-8];
367                  sum += qlp_coeff[6] * data[i-7];
368                  sum += qlp_coeff[5] * data[i-6];
369                  sum += qlp_coeff[4] * data[i-5];
370                  sum += qlp_coeff[3] * data[i-4];
371                  sum += qlp_coeff[2] * data[i-3];
372                  sum += qlp_coeff[1] * data[i-2];
373                  sum += qlp_coeff[0] * data[i-1];
374                  residual[i] = data[i] - (sum >> lp_quantization);
375               }
376            }
377            else { /* order == 9 */
378               for(i = 0; i < (int)data_len; i++) {
379                  sum = 0;
380                  sum += qlp_coeff[8] * data[i-9];
381                  sum += qlp_coeff[7] * data[i-8];
382                  sum += qlp_coeff[6] * data[i-7];
383                  sum += qlp_coeff[5] * data[i-6];
384                  sum += qlp_coeff[4] * data[i-5];
385                  sum += qlp_coeff[3] * data[i-4];
386                  sum += qlp_coeff[2] * data[i-3];
387                  sum += qlp_coeff[1] * data[i-2];
388                  sum += qlp_coeff[0] * data[i-1];
389                  residual[i] = data[i] - (sum >> lp_quantization);
390               }
391            }
392         }
393      }
394      else if(order > 4) {
395         if(order > 6) {
396            if(order == 8) {
397               for(i = 0; i < (int)data_len; i++) {
398                  sum = 0;
399                  sum += qlp_coeff[7] * data[i-8];
400                  sum += qlp_coeff[6] * data[i-7];
401                  sum += qlp_coeff[5] * data[i-6];
402                  sum += qlp_coeff[4] * data[i-5];
403                  sum += qlp_coeff[3] * data[i-4];
404                  sum += qlp_coeff[2] * data[i-3];
405                  sum += qlp_coeff[1] * data[i-2];
406                  sum += qlp_coeff[0] * data[i-1];
407                  residual[i] = data[i] - (sum >> lp_quantization);
408               }
409            }
410            else { /* order == 7 */
411               for(i = 0; i < (int)data_len; i++) {
412                  sum = 0;
413                  sum += qlp_coeff[6] * data[i-7];
414                  sum += qlp_coeff[5] * data[i-6];
415                  sum += qlp_coeff[4] * data[i-5];
416                  sum += qlp_coeff[3] * data[i-4];
417                  sum += qlp_coeff[2] * data[i-3];
418                  sum += qlp_coeff[1] * data[i-2];
419                  sum += qlp_coeff[0] * data[i-1];
420                  residual[i] = data[i] - (sum >> lp_quantization);
421               }
422            }
423         }
424         else {
425            if(order == 6) {
426               for(i = 0; i < (int)data_len; i++) {
427                  sum = 0;
428                  sum += qlp_coeff[5] * data[i-6];
429                  sum += qlp_coeff[4] * data[i-5];
430                  sum += qlp_coeff[3] * data[i-4];
431                  sum += qlp_coeff[2] * data[i-3];
432                  sum += qlp_coeff[1] * data[i-2];
433                  sum += qlp_coeff[0] * data[i-1];
434                  residual[i] = data[i] - (sum >> lp_quantization);
435               }
436            }
437            else { /* order == 5 */
438               for(i = 0; i < (int)data_len; i++) {
439                  sum = 0;
440                  sum += qlp_coeff[4] * data[i-5];
441                  sum += qlp_coeff[3] * data[i-4];
442                  sum += qlp_coeff[2] * data[i-3];
443                  sum += qlp_coeff[1] * data[i-2];
444                  sum += qlp_coeff[0] * data[i-1];
445                  residual[i] = data[i] - (sum >> lp_quantization);
446               }
447            }
448         }
449      }
450      else {
451         if(order > 2) {
452            if(order == 4) {
453               for(i = 0; i < (int)data_len; i++) {
454                  sum = 0;
455                  sum += qlp_coeff[3] * data[i-4];
456                  sum += qlp_coeff[2] * data[i-3];
457                  sum += qlp_coeff[1] * data[i-2];
458                  sum += qlp_coeff[0] * data[i-1];
459                  residual[i] = data[i] - (sum >> lp_quantization);
460               }
461            }
462            else { /* order == 3 */
463               for(i = 0; i < (int)data_len; i++) {
464                  sum = 0;
465                  sum += qlp_coeff[2] * data[i-3];
466                  sum += qlp_coeff[1] * data[i-2];
467                  sum += qlp_coeff[0] * data[i-1];
468                  residual[i] = data[i] - (sum >> lp_quantization);
469               }
470            }
471         }
472         else {
473            if(order == 2) {
474               for(i = 0; i < (int)data_len; i++) {
475                  sum = 0;
476                  sum += qlp_coeff[1] * data[i-2];
477                  sum += qlp_coeff[0] * data[i-1];
478                  residual[i] = data[i] - (sum >> lp_quantization);
479               }
480            }
481            else { /* order == 1 */
482               for(i = 0; i < (int)data_len; i++)
483                  residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
484            }
485         }
486      }
487   }
488   else { /* order > 12 */
489      for(i = 0; i < (int)data_len; i++) {
490         sum = 0;
491         switch(order) {
492            case 32: sum += qlp_coeff[31] * data[i-32];
493            case 31: sum += qlp_coeff[30] * data[i-31];
494            case 30: sum += qlp_coeff[29] * data[i-30];
495            case 29: sum += qlp_coeff[28] * data[i-29];
496            case 28: sum += qlp_coeff[27] * data[i-28];
497            case 27: sum += qlp_coeff[26] * data[i-27];
498            case 26: sum += qlp_coeff[25] * data[i-26];
499            case 25: sum += qlp_coeff[24] * data[i-25];
500            case 24: sum += qlp_coeff[23] * data[i-24];
501            case 23: sum += qlp_coeff[22] * data[i-23];
502            case 22: sum += qlp_coeff[21] * data[i-22];
503            case 21: sum += qlp_coeff[20] * data[i-21];
504            case 20: sum += qlp_coeff[19] * data[i-20];
505            case 19: sum += qlp_coeff[18] * data[i-19];
506            case 18: sum += qlp_coeff[17] * data[i-18];
507            case 17: sum += qlp_coeff[16] * data[i-17];
508            case 16: sum += qlp_coeff[15] * data[i-16];
509            case 15: sum += qlp_coeff[14] * data[i-15];
510            case 14: sum += qlp_coeff[13] * data[i-14];
511            case 13: sum += qlp_coeff[12] * data[i-13];
512                     sum += qlp_coeff[11] * data[i-12];
513                     sum += qlp_coeff[10] * data[i-11];
514                     sum += qlp_coeff[ 9] * data[i-10];
515                     sum += qlp_coeff[ 8] * data[i- 9];
516                     sum += qlp_coeff[ 7] * data[i- 8];
517                     sum += qlp_coeff[ 6] * data[i- 7];
518                     sum += qlp_coeff[ 5] * data[i- 6];
519                     sum += qlp_coeff[ 4] * data[i- 5];
520                     sum += qlp_coeff[ 3] * data[i- 4];
521                     sum += qlp_coeff[ 2] * data[i- 3];
522                     sum += qlp_coeff[ 1] * data[i- 2];
523                     sum += qlp_coeff[ 0] * data[i- 1];
524         }
525         residual[i] = data[i] - (sum >> lp_quantization);
526      }
527   }
528}
529#endif
530
531void 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[])
532#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
533{
534   unsigned i, j;
535   FLAC__int64 sum;
536   const FLAC__int32 *history;
537
538#ifdef FLAC__OVERFLOW_DETECT_VERBOSE
539   fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
540   for(i=0;i<order;i++)
541      fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
542   fprintf(stderr,"\n");
543#endif
544   FLAC__ASSERT(order > 0);
545
546   for(i = 0; i < data_len; i++) {
547      sum = 0;
548      history = data;
549      for(j = 0; j < order; j++)
550         sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
551      if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
552#if defined _MSC_VER
553         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
554#else
555         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
556#endif
557         break;
558      }
559      if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
560#if defined _MSC_VER
561         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));
562#else
563         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)));
564#endif
565         break;
566      }
567      *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
568   }
569}
570#else /* fully unrolled version for normal use */
571{
572   int i;
573   FLAC__int64 sum;
574
575   FLAC__ASSERT(order > 0);
576   FLAC__ASSERT(order <= 32);
577
578   /*
579    * We do unique versions up to 12th order since that's the subset limit.
580    * Also they are roughly ordered to match frequency of occurrence to
581    * minimize branching.
582    */
583   if(order <= 12) {
584      if(order > 8) {
585         if(order > 10) {
586            if(order == 12) {
587               for(i = 0; i < (int)data_len; i++) {
588                  sum = 0;
589                  sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
590                  sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
591                  sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
592                  sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
593                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
594                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
595                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
596                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
597                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
598                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
599                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
600                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
601                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
602               }
603            }
604            else { /* order == 11 */
605               for(i = 0; i < (int)data_len; i++) {
606                  sum = 0;
607                  sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
608                  sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
609                  sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
610                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
611                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
612                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
613                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
614                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
615                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
616                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
617                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
618                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
619               }
620            }
621         }
622         else {
623            if(order == 10) {
624               for(i = 0; i < (int)data_len; i++) {
625                  sum = 0;
626                  sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
627                  sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
628                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
629                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
630                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
631                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
632                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
633                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
634                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
635                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
636                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
637               }
638            }
639            else { /* order == 9 */
640               for(i = 0; i < (int)data_len; i++) {
641                  sum = 0;
642                  sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
643                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
644                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
645                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
646                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
647                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
648                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
649                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
650                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
651                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
652               }
653            }
654         }
655      }
656      else if(order > 4) {
657         if(order > 6) {
658            if(order == 8) {
659               for(i = 0; i < (int)data_len; i++) {
660                  sum = 0;
661                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
662                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
663                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
664                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
665                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
666                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
667                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
668                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
669                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
670               }
671            }
672            else { /* order == 7 */
673               for(i = 0; i < (int)data_len; i++) {
674                  sum = 0;
675                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
676                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
677                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
678                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
679                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
680                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
681                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
682                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
683               }
684            }
685         }
686         else {
687            if(order == 6) {
688               for(i = 0; i < (int)data_len; i++) {
689                  sum = 0;
690                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
691                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
692                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
693                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
694                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
695                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
696                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
697               }
698            }
699            else { /* order == 5 */
700               for(i = 0; i < (int)data_len; i++) {
701                  sum = 0;
702                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
703                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
704                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
705                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
706                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
707                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
708               }
709            }
710         }
711      }
712      else {
713         if(order > 2) {
714            if(order == 4) {
715               for(i = 0; i < (int)data_len; i++) {
716                  sum = 0;
717                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
718                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
719                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
720                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
721                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
722               }
723            }
724            else { /* order == 3 */
725               for(i = 0; i < (int)data_len; i++) {
726                  sum = 0;
727                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
728                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
729                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
730                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
731               }
732            }
733         }
734         else {
735            if(order == 2) {
736               for(i = 0; i < (int)data_len; i++) {
737                  sum = 0;
738                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
739                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
740                  residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
741               }
742            }
743            else { /* order == 1 */
744               for(i = 0; i < (int)data_len; i++)
745                  residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
746            }
747         }
748      }
749   }
750   else { /* order > 12 */
751      for(i = 0; i < (int)data_len; i++) {
752         sum = 0;
753         switch(order) {
754            case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
755            case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
756            case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
757            case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
758            case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
759            case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
760            case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
761            case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
762            case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
763            case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
764            case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
765            case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
766            case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
767            case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
768            case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
769            case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
770            case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
771            case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
772            case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
773            case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
774                     sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
775                     sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
776                     sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
777                     sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
778                     sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
779                     sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
780                     sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
781                     sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
782                     sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
783                     sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
784                     sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
785                     sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
786         }
787         residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
788      }
789   }
790}
791#endif
792
793#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
794
795void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
796#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
797{
798   FLAC__int64 sumo;
799   unsigned i, j;
800   FLAC__int32 sum;
801   const FLAC__int32 *r = residual, *history;
802
803#ifdef FLAC__OVERFLOW_DETECT_VERBOSE
804   fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
805   for(i=0;i<order;i++)
806      fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
807   fprintf(stderr,"\n");
808#endif
809   FLAC__ASSERT(order > 0);
810
811   for(i = 0; i < data_len; i++) {
812      sumo = 0;
813      sum = 0;
814      history = data;
815      for(j = 0; j < order; j++) {
816         sum += qlp_coeff[j] * (*(--history));
817         sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
818#if defined _MSC_VER
819         if(sumo > 2147483647I64 || sumo < -2147483648I64)
820            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);
821#else
822         if(sumo > 2147483647ll || sumo < -2147483648ll)
823            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);
824#endif
825      }
826      *(data++) = *(r++) + (sum >> lp_quantization);
827   }
828
829   /* Here's a slower but clearer version:
830   for(i = 0; i < data_len; i++) {
831      sum = 0;
832      for(j = 0; j < order; j++)
833         sum += qlp_coeff[j] * data[i-j-1];
834      data[i] = residual[i] + (sum >> lp_quantization);
835   }
836   */
837}
838#else /* fully unrolled version for normal use */
839{
840   int i;
841   FLAC__int32 sum;
842
843   FLAC__ASSERT(order > 0);
844   FLAC__ASSERT(order <= 32);
845
846   /*
847    * We do unique versions up to 12th order since that's the subset limit.
848    * Also they are roughly ordered to match frequency of occurrence to
849    * minimize branching.
850    */
851   if(order <= 12) {
852      if(order > 8) {
853         if(order > 10) {
854            if(order == 12) {
855               for(i = 0; i < (int)data_len; i++) {
856                  sum = 0;
857                  sum += qlp_coeff[11] * data[i-12];
858                  sum += qlp_coeff[10] * data[i-11];
859                  sum += qlp_coeff[9] * data[i-10];
860                  sum += qlp_coeff[8] * data[i-9];
861                  sum += qlp_coeff[7] * data[i-8];
862                  sum += qlp_coeff[6] * data[i-7];
863                  sum += qlp_coeff[5] * data[i-6];
864                  sum += qlp_coeff[4] * data[i-5];
865                  sum += qlp_coeff[3] * data[i-4];
866                  sum += qlp_coeff[2] * data[i-3];
867                  sum += qlp_coeff[1] * data[i-2];
868                  sum += qlp_coeff[0] * data[i-1];
869                  data[i] = residual[i] + (sum >> lp_quantization);
870               }
871            }
872            else { /* order == 11 */
873               for(i = 0; i < (int)data_len; i++) {
874                  sum = 0;
875                  sum += qlp_coeff[10] * data[i-11];
876                  sum += qlp_coeff[9] * data[i-10];
877                  sum += qlp_coeff[8] * data[i-9];
878                  sum += qlp_coeff[7] * data[i-8];
879                  sum += qlp_coeff[6] * data[i-7];
880                  sum += qlp_coeff[5] * data[i-6];
881                  sum += qlp_coeff[4] * data[i-5];
882                  sum += qlp_coeff[3] * data[i-4];
883                  sum += qlp_coeff[2] * data[i-3];
884                  sum += qlp_coeff[1] * data[i-2];
885                  sum += qlp_coeff[0] * data[i-1];
886                  data[i] = residual[i] + (sum >> lp_quantization);
887               }
888            }
889         }
890         else {
891            if(order == 10) {
892               for(i = 0; i < (int)data_len; i++) {
893                  sum = 0;
894                  sum += qlp_coeff[9] * data[i-10];
895                  sum += qlp_coeff[8] * data[i-9];
896                  sum += qlp_coeff[7] * data[i-8];
897                  sum += qlp_coeff[6] * data[i-7];
898                  sum += qlp_coeff[5] * data[i-6];
899                  sum += qlp_coeff[4] * data[i-5];
900                  sum += qlp_coeff[3] * data[i-4];
901                  sum += qlp_coeff[2] * data[i-3];
902                  sum += qlp_coeff[1] * data[i-2];
903                  sum += qlp_coeff[0] * data[i-1];
904                  data[i] = residual[i] + (sum >> lp_quantization);
905               }
906            }
907            else { /* order == 9 */
908               for(i = 0; i < (int)data_len; i++) {
909                  sum = 0;
910                  sum += qlp_coeff[8] * data[i-9];
911                  sum += qlp_coeff[7] * data[i-8];
912                  sum += qlp_coeff[6] * data[i-7];
913                  sum += qlp_coeff[5] * data[i-6];
914                  sum += qlp_coeff[4] * data[i-5];
915                  sum += qlp_coeff[3] * data[i-4];
916                  sum += qlp_coeff[2] * data[i-3];
917                  sum += qlp_coeff[1] * data[i-2];
918                  sum += qlp_coeff[0] * data[i-1];
919                  data[i] = residual[i] + (sum >> lp_quantization);
920               }
921            }
922         }
923      }
924      else if(order > 4) {
925         if(order > 6) {
926            if(order == 8) {
927               for(i = 0; i < (int)data_len; i++) {
928                  sum = 0;
929                  sum += qlp_coeff[7] * data[i-8];
930                  sum += qlp_coeff[6] * data[i-7];
931                  sum += qlp_coeff[5] * data[i-6];
932                  sum += qlp_coeff[4] * data[i-5];
933                  sum += qlp_coeff[3] * data[i-4];
934                  sum += qlp_coeff[2] * data[i-3];
935                  sum += qlp_coeff[1] * data[i-2];
936                  sum += qlp_coeff[0] * data[i-1];
937                  data[i] = residual[i] + (sum >> lp_quantization);
938               }
939            }
940            else { /* order == 7 */
941               for(i = 0; i < (int)data_len; i++) {
942                  sum = 0;
943                  sum += qlp_coeff[6] * data[i-7];
944                  sum += qlp_coeff[5] * data[i-6];
945                  sum += qlp_coeff[4] * data[i-5];
946                  sum += qlp_coeff[3] * data[i-4];
947                  sum += qlp_coeff[2] * data[i-3];
948                  sum += qlp_coeff[1] * data[i-2];
949                  sum += qlp_coeff[0] * data[i-1];
950                  data[i] = residual[i] + (sum >> lp_quantization);
951               }
952            }
953         }
954         else {
955            if(order == 6) {
956               for(i = 0; i < (int)data_len; i++) {
957                  sum = 0;
958                  sum += qlp_coeff[5] * data[i-6];
959                  sum += qlp_coeff[4] * data[i-5];
960                  sum += qlp_coeff[3] * data[i-4];
961                  sum += qlp_coeff[2] * data[i-3];
962                  sum += qlp_coeff[1] * data[i-2];
963                  sum += qlp_coeff[0] * data[i-1];
964                  data[i] = residual[i] + (sum >> lp_quantization);
965               }
966            }
967            else { /* order == 5 */
968               for(i = 0; i < (int)data_len; i++) {
969                  sum = 0;
970                  sum += qlp_coeff[4] * data[i-5];
971                  sum += qlp_coeff[3] * data[i-4];
972                  sum += qlp_coeff[2] * data[i-3];
973                  sum += qlp_coeff[1] * data[i-2];
974                  sum += qlp_coeff[0] * data[i-1];
975                  data[i] = residual[i] + (sum >> lp_quantization);
976               }
977            }
978         }
979      }
980      else {
981         if(order > 2) {
982            if(order == 4) {
983               for(i = 0; i < (int)data_len; i++) {
984                  sum = 0;
985                  sum += qlp_coeff[3] * data[i-4];
986                  sum += qlp_coeff[2] * data[i-3];
987                  sum += qlp_coeff[1] * data[i-2];
988                  sum += qlp_coeff[0] * data[i-1];
989                  data[i] = residual[i] + (sum >> lp_quantization);
990               }
991            }
992            else { /* order == 3 */
993               for(i = 0; i < (int)data_len; i++) {
994                  sum = 0;
995                  sum += qlp_coeff[2] * data[i-3];
996                  sum += qlp_coeff[1] * data[i-2];
997                  sum += qlp_coeff[0] * data[i-1];
998                  data[i] = residual[i] + (sum >> lp_quantization);
999               }
1000            }
1001         }
1002         else {
1003            if(order == 2) {
1004               for(i = 0; i < (int)data_len; i++) {
1005                  sum = 0;
1006                  sum += qlp_coeff[1] * data[i-2];
1007                  sum += qlp_coeff[0] * data[i-1];
1008                  data[i] = residual[i] + (sum >> lp_quantization);
1009               }
1010            }
1011            else { /* order == 1 */
1012               for(i = 0; i < (int)data_len; i++)
1013                  data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
1014            }
1015         }
1016      }
1017   }
1018   else { /* order > 12 */
1019      for(i = 0; i < (int)data_len; i++) {
1020         sum = 0;
1021         switch(order) {
1022            case 32: sum += qlp_coeff[31] * data[i-32];
1023            case 31: sum += qlp_coeff[30] * data[i-31];
1024            case 30: sum += qlp_coeff[29] * data[i-30];
1025            case 29: sum += qlp_coeff[28] * data[i-29];
1026            case 28: sum += qlp_coeff[27] * data[i-28];
1027            case 27: sum += qlp_coeff[26] * data[i-27];
1028            case 26: sum += qlp_coeff[25] * data[i-26];
1029            case 25: sum += qlp_coeff[24] * data[i-25];
1030            case 24: sum += qlp_coeff[23] * data[i-24];
1031            case 23: sum += qlp_coeff[22] * data[i-23];
1032            case 22: sum += qlp_coeff[21] * data[i-22];
1033            case 21: sum += qlp_coeff[20] * data[i-21];
1034            case 20: sum += qlp_coeff[19] * data[i-20];
1035            case 19: sum += qlp_coeff[18] * data[i-19];
1036            case 18: sum += qlp_coeff[17] * data[i-18];
1037            case 17: sum += qlp_coeff[16] * data[i-17];
1038            case 16: sum += qlp_coeff[15] * data[i-16];
1039            case 15: sum += qlp_coeff[14] * data[i-15];
1040            case 14: sum += qlp_coeff[13] * data[i-14];
1041            case 13: sum += qlp_coeff[12] * data[i-13];
1042                     sum += qlp_coeff[11] * data[i-12];
1043                     sum += qlp_coeff[10] * data[i-11];
1044                     sum += qlp_coeff[ 9] * data[i-10];
1045                     sum += qlp_coeff[ 8] * data[i- 9];
1046                     sum += qlp_coeff[ 7] * data[i- 8];
1047                     sum += qlp_coeff[ 6] * data[i- 7];
1048                     sum += qlp_coeff[ 5] * data[i- 6];
1049                     sum += qlp_coeff[ 4] * data[i- 5];
1050                     sum += qlp_coeff[ 3] * data[i- 4];
1051                     sum += qlp_coeff[ 2] * data[i- 3];
1052                     sum += qlp_coeff[ 1] * data[i- 2];
1053                     sum += qlp_coeff[ 0] * data[i- 1];
1054         }
1055         data[i] = residual[i] + (sum >> lp_quantization);
1056      }
1057   }
1058}
1059#endif
1060
1061void 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[])
1062#if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
1063{
1064   unsigned i, j;
1065   FLAC__int64 sum;
1066   const FLAC__int32 *r = residual, *history;
1067
1068#ifdef FLAC__OVERFLOW_DETECT_VERBOSE
1069   fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
1070   for(i=0;i<order;i++)
1071      fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
1072   fprintf(stderr,"\n");
1073#endif
1074   FLAC__ASSERT(order > 0);
1075
1076   for(i = 0; i < data_len; i++) {
1077      sum = 0;
1078      history = data;
1079      for(j = 0; j < order; j++)
1080         sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
1081      if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
1082#ifdef _MSC_VER
1083         fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
1084#else
1085         fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
1086#endif
1087         break;
1088      }
1089      if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
1090#ifdef _MSC_VER
1091         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));
1092#else
1093         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)));
1094#endif
1095         break;
1096      }
1097      *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
1098   }
1099}
1100#else /* fully unrolled version for normal use */
1101{
1102   int i;
1103   FLAC__int64 sum;
1104
1105   FLAC__ASSERT(order > 0);
1106   FLAC__ASSERT(order <= 32);
1107
1108   /*
1109    * We do unique versions up to 12th order since that's the subset limit.
1110    * Also they are roughly ordered to match frequency of occurrence to
1111    * minimize branching.
1112    */
1113   if(order <= 12) {
1114      if(order > 8) {
1115         if(order > 10) {
1116            if(order == 12) {
1117               for(i = 0; i < (int)data_len; i++) {
1118                  sum = 0;
1119                  sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
1120                  sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
1121                  sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
1122                  sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
1123                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
1124                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
1125                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
1126                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
1127                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
1128                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1129                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1130                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1131                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1132               }
1133            }
1134            else { /* order == 11 */
1135               for(i = 0; i < (int)data_len; i++) {
1136                  sum = 0;
1137                  sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
1138                  sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
1139                  sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
1140                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
1141                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
1142                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
1143                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
1144                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
1145                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1146                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1147                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1148                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1149               }
1150            }
1151         }
1152         else {
1153            if(order == 10) {
1154               for(i = 0; i < (int)data_len; i++) {
1155                  sum = 0;
1156                  sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
1157                  sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
1158                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
1159                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
1160                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
1161                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
1162                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
1163                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1164                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1165                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1166                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1167               }
1168            }
1169            else { /* order == 9 */
1170               for(i = 0; i < (int)data_len; i++) {
1171                  sum = 0;
1172                  sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
1173                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
1174                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
1175                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
1176                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
1177                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
1178                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1179                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1180                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1181                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1182               }
1183            }
1184         }
1185      }
1186      else if(order > 4) {
1187         if(order > 6) {
1188            if(order == 8) {
1189               for(i = 0; i < (int)data_len; i++) {
1190                  sum = 0;
1191                  sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
1192                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
1193                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
1194                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
1195                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
1196                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1197                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1198                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1199                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1200               }
1201            }
1202            else { /* order == 7 */
1203               for(i = 0; i < (int)data_len; i++) {
1204                  sum = 0;
1205                  sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
1206                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
1207                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
1208                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
1209                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1210                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1211                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1212                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1213               }
1214            }
1215         }
1216         else {
1217            if(order == 6) {
1218               for(i = 0; i < (int)data_len; i++) {
1219                  sum = 0;
1220                  sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
1221                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
1222                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
1223                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1224                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1225                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1226                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1227               }
1228            }
1229            else { /* order == 5 */
1230               for(i = 0; i < (int)data_len; i++) {
1231                  sum = 0;
1232                  sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
1233                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
1234                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1235                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1236                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1237                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1238               }
1239            }
1240         }
1241      }
1242      else {
1243         if(order > 2) {
1244            if(order == 4) {
1245               for(i = 0; i < (int)data_len; i++) {
1246                  sum = 0;
1247                  sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
1248                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1249                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1250                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1251                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1252               }
1253            }
1254            else { /* order == 3 */
1255               for(i = 0; i < (int)data_len; i++) {
1256                  sum = 0;
1257                  sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
1258                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1259                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1260                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1261               }
1262            }
1263         }
1264         else {
1265            if(order == 2) {
1266               for(i = 0; i < (int)data_len; i++) {
1267                  sum = 0;
1268                  sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
1269                  sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
1270                  data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1271               }
1272            }
1273            else { /* order == 1 */
1274               for(i = 0; i < (int)data_len; i++)
1275                  data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
1276            }
1277         }
1278      }
1279   }
1280   else { /* order > 12 */
1281      for(i = 0; i < (int)data_len; i++) {
1282         sum = 0;
1283         switch(order) {
1284            case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
1285            case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
1286            case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
1287            case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
1288            case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
1289            case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
1290            case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
1291            case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
1292            case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
1293            case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
1294            case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
1295            case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
1296            case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
1297            case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
1298            case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
1299            case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
1300            case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
1301            case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
1302            case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
1303            case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
1304                     sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
1305                     sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
1306                     sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
1307                     sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
1308                     sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
1309                     sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
1310                     sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
1311                     sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
1312                     sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
1313                     sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
1314                     sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
1315                     sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
1316         }
1317         data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
1318      }
1319   }
1320}
1321#endif
1322
1323#ifndef FLAC__INTEGER_ONLY_LIBRARY
1324
1325FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
1326{
1327   FLAC__double error_scale;
1328
1329   FLAC__ASSERT(total_samples > 0);
1330
1331   error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
1332
1333   return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
1334}
1335
1336FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
1337{
1338   if(lpc_error > 0.0) {
1339      FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
1340      if(bps >= 0.0)
1341         return bps;
1342      else
1343         return 0.0;
1344   }
1345   else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
1346      return 1e32;
1347   }
1348   else {
1349      return 0.0;
1350   }
1351}
1352
1353unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
1354{
1355   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 */
1356   FLAC__double bits, best_bits, error_scale;
1357
1358   FLAC__ASSERT(max_order > 0);
1359   FLAC__ASSERT(total_samples > 0);
1360
1361   error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
1362
1363   best_index = 0;
1364   best_bits = (unsigned)(-1);
1365
1366   for(index = 0, order = 1; index < max_order; index++, order++) {
1367      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);
1368      if(bits < best_bits) {
1369         best_index = index;
1370         best_bits = bits;
1371      }
1372   }
1373
1374   return best_index+1; /* +1 since index of lpc_error[] is order-1 */
1375}
1376
1377#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
src/lib/libflac/libflac/stream_decoder.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include <stdio.h>
37#include <stdlib.h> /* for malloc() */
38#include <string.h> /* for memset/memcpy() */
39#include <sys/stat.h> /* for stat() */
40#include <sys/types.h> /* for off_t */
41#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
42#if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
43#define fseeko fseek
44#define ftello ftell
45#endif
46#endif
47#include "flac/assert.h"
48#include "share/alloc.h"
49#include "protected/stream_decoder.h"
50#include "private/bitreader.h"
51#include "private/bitmath.h"
52#include "private/cpu.h"
53#include "private/crc.h"
54#include "private/fixed.h"
55#include "private/format.h"
56#include "private/lpc.h"
57#include "private/md5.h"
58#include "private/memory.h"
59
60#ifdef max
61#undef max
62#endif
63#define max(a,b) ((a)>(b)?(a):(b))
64
65/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
66#ifdef _MSC_VER
67#define FLAC__U64L(x) x
68#else
69#define FLAC__U64L(x) x##LLU
70#endif
71
72
73/* technically this should be in an "export.c" but this is convenient enough */
74FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
75#if FLAC__HAS_OGG
76   1
77#else
78   0
79#endif
80;
81
82
83/***********************************************************************
84 *
85 * Private static data
86 *
87 ***********************************************************************/
88
89static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
90
91/***********************************************************************
92 *
93 * Private class method prototypes
94 *
95 ***********************************************************************/
96
97static void set_defaults_(FLAC__StreamDecoder *decoder);
98static FILE *get_binary_stdin_(void);
99static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
100static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
101static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
102static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
103static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
104static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
105static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
106static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
107static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
108static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
109static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
110static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
111static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
112static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
113static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
114static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
115static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
116static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
117static 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);
118static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
119static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
120#if FLAC__HAS_OGG
121static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
122static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
123#endif
124static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
125static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
126static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
127#if FLAC__HAS_OGG
128static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
129#endif
130static FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
131static FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
132static FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
133static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
134static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
135
136/***********************************************************************
137 *
138 * Private class data
139 *
140 ***********************************************************************/
141
142typedef struct FLAC__StreamDecoderPrivate {
143#if FLAC__HAS_OGG
144   FLAC__bool is_ogg;
145#endif
146   FLAC__StreamDecoderReadCallback read_callback;
147   FLAC__StreamDecoderSeekCallback seek_callback;
148   FLAC__StreamDecoderTellCallback tell_callback;
149   FLAC__StreamDecoderLengthCallback length_callback;
150   FLAC__StreamDecoderEofCallback eof_callback;
151   FLAC__StreamDecoderWriteCallback write_callback;
152   FLAC__StreamDecoderMetadataCallback metadata_callback;
153   FLAC__StreamDecoderErrorCallback error_callback;
154   /* generic 32-bit datapath: */
155   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[]);
156   /* generic 64-bit datapath: */
157   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[]);
158   /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
159   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[]);
160   /* 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: */
161   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[]);
162   FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
163   void *client_data;
164   FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
165   FLAC__BitReader *input;
166   FLAC__int32 *output[FLAC__MAX_CHANNELS];
167   FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
168   FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
169   unsigned output_capacity, output_channels;
170   FLAC__uint32 fixed_block_size, next_fixed_block_size;
171   FLAC__uint64 samples_decoded;
172   FLAC__bool has_stream_info, has_seek_table;
173   FLAC__StreamMetadata stream_info;
174   FLAC__StreamMetadata seek_table;
175   FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
176   FLAC__byte *metadata_filter_ids;
177   size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
178   FLAC__Frame frame;
179   FLAC__bool cached; /* true if there is a byte in lookahead */
180   FLAC__CPUInfo cpuinfo;
181   FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
182   FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
183   /* unaligned (original) pointers to allocated data */
184   FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
185   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 */
186   FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
187   FLAC__bool is_seeking;
188   FLAC__MD5Context md5context;
189   FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
190   /* (the rest of these are only used for seeking) */
191   FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
192   FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
193   FLAC__uint64 target_sample;
194   unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
195#if FLAC__HAS_OGG
196   FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
197#endif
198} FLAC__StreamDecoderPrivate;
199
200/***********************************************************************
201 *
202 * Public static class data
203 *
204 ***********************************************************************/
205
206FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
207   "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
208   "FLAC__STREAM_DECODER_READ_METADATA",
209   "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
210   "FLAC__STREAM_DECODER_READ_FRAME",
211   "FLAC__STREAM_DECODER_END_OF_STREAM",
212   "FLAC__STREAM_DECODER_OGG_ERROR",
213   "FLAC__STREAM_DECODER_SEEK_ERROR",
214   "FLAC__STREAM_DECODER_ABORTED",
215   "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
216   "FLAC__STREAM_DECODER_UNINITIALIZED"
217};
218
219FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
220   "FLAC__STREAM_DECODER_INIT_STATUS_OK",
221   "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
222   "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
223   "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
224   "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
225   "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
226};
227
228FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
229   "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
230   "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
231   "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
232};
233
234FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
235   "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
236   "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
237   "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
238};
239
240FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
241   "FLAC__STREAM_DECODER_TELL_STATUS_OK",
242   "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
243   "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
244};
245
246FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
247   "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
248   "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
249   "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
250};
251
252FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
253   "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
254   "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
255};
256
257FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
258   "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
259   "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
260   "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
261   "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
262};
263
264/***********************************************************************
265 *
266 * Class constructor/destructor
267 *
268 ***********************************************************************/
269FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
270{
271   FLAC__StreamDecoder *decoder;
272   unsigned i;
273
274   FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
275
276   decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
277   if(decoder == 0) {
278      return 0;
279   }
280
281   decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
282   if(decoder->protected_ == 0) {
283      free(decoder);
284      return 0;
285   }
286
287   decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
288   if(decoder->private_ == 0) {
289      free(decoder->protected_);
290      free(decoder);
291      return 0;
292   }
293
294   decoder->private_->input = FLAC__bitreader_new();
295   if(decoder->private_->input == 0) {
296      free(decoder->private_);
297      free(decoder->protected_);
298      free(decoder);
299      return 0;
300   }
301
302   decoder->private_->metadata_filter_ids_capacity = 16;
303   if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
304      FLAC__bitreader_delete(decoder->private_->input);
305      free(decoder->private_);
306      free(decoder->protected_);
307      free(decoder);
308      return 0;
309   }
310
311   for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
312      decoder->private_->output[i] = 0;
313      decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
314   }
315
316   decoder->private_->output_capacity = 0;
317   decoder->private_->output_channels = 0;
318   decoder->private_->has_seek_table = false;
319
320   for(i = 0; i < FLAC__MAX_CHANNELS; i++)
321      FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
322
323   decoder->private_->file = 0;
324
325   set_defaults_(decoder);
326
327   decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
328
329   return decoder;
330}
331
332FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
333{
334   unsigned i;
335
336   FLAC__ASSERT(0 != decoder);
337   FLAC__ASSERT(0 != decoder->protected_);
338   FLAC__ASSERT(0 != decoder->private_);
339   FLAC__ASSERT(0 != decoder->private_->input);
340
341   (void)FLAC__stream_decoder_finish(decoder);
342
343   if(0 != decoder->private_->metadata_filter_ids)
344      free(decoder->private_->metadata_filter_ids);
345
346   FLAC__bitreader_delete(decoder->private_->input);
347
348   for(i = 0; i < FLAC__MAX_CHANNELS; i++)
349      FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
350
351   free(decoder->private_);
352   free(decoder->protected_);
353   free(decoder);
354}
355
356/***********************************************************************
357 *
358 * Public class methods
359 *
360 ***********************************************************************/
361
362static FLAC__StreamDecoderInitStatus init_stream_internal_(
363   FLAC__StreamDecoder *decoder,
364   FLAC__StreamDecoderReadCallback read_callback,
365   FLAC__StreamDecoderSeekCallback seek_callback,
366   FLAC__StreamDecoderTellCallback tell_callback,
367   FLAC__StreamDecoderLengthCallback length_callback,
368   FLAC__StreamDecoderEofCallback eof_callback,
369   FLAC__StreamDecoderWriteCallback write_callback,
370   FLAC__StreamDecoderMetadataCallback metadata_callback,
371   FLAC__StreamDecoderErrorCallback error_callback,
372   void *client_data,
373   FLAC__bool is_ogg
374)
375{
376   FLAC__ASSERT(0 != decoder);
377
378   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
379      return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
380
381#if !FLAC__HAS_OGG
382   if(is_ogg)
383      return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
384#endif
385
386   if(
387      0 == read_callback ||
388      0 == write_callback ||
389      0 == error_callback ||
390      (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
391   )
392      return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
393
394#if FLAC__HAS_OGG
395   decoder->private_->is_ogg = is_ogg;
396   if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
397      return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
398#endif
399
400   /*
401    * get the CPU info and set the function pointers
402    */
403   FLAC__cpu_info(&decoder->private_->cpuinfo);
404   /* first default to the non-asm routines */
405   decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
406   decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
407   decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
408   decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
409   decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
410   /* now override with asm where appropriate */
411#ifndef FLAC__NO_ASM
412   if(decoder->private_->cpuinfo.use_asm) {
413#ifdef FLAC__CPU_IA32
414      FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
415#ifdef FLAC__HAS_NASM
416#if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
417      if(decoder->private_->cpuinfo.data.ia32.bswap)
418         decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
419#endif
420      if(decoder->private_->cpuinfo.data.ia32.mmx) {
421         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
422         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
423         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
424      }
425      else {
426         decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
427         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
428         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
429      }
430#endif
431#elif defined FLAC__CPU_PPC
432      FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
433      if(decoder->private_->cpuinfo.data.ppc.altivec) {
434         decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
435         decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
436      }
437#endif
438   }
439#endif
440
441   /* from here on, errors are fatal */
442
443   if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
444      decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
445      return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
446   }
447
448   decoder->private_->read_callback = read_callback;
449   decoder->private_->seek_callback = seek_callback;
450   decoder->private_->tell_callback = tell_callback;
451   decoder->private_->length_callback = length_callback;
452   decoder->private_->eof_callback = eof_callback;
453   decoder->private_->write_callback = write_callback;
454   decoder->private_->metadata_callback = metadata_callback;
455   decoder->private_->error_callback = error_callback;
456   decoder->private_->client_data = client_data;
457   decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
458   decoder->private_->samples_decoded = 0;
459   decoder->private_->has_stream_info = false;
460   decoder->private_->cached = false;
461
462   decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
463   decoder->private_->is_seeking = false;
464
465   decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
466   if(!FLAC__stream_decoder_reset(decoder)) {
467      /* above call sets the state for us */
468      return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
469   }
470
471   return FLAC__STREAM_DECODER_INIT_STATUS_OK;
472}
473
474FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
475   FLAC__StreamDecoder *decoder,
476   FLAC__StreamDecoderReadCallback read_callback,
477   FLAC__StreamDecoderSeekCallback seek_callback,
478   FLAC__StreamDecoderTellCallback tell_callback,
479   FLAC__StreamDecoderLengthCallback length_callback,
480   FLAC__StreamDecoderEofCallback eof_callback,
481   FLAC__StreamDecoderWriteCallback write_callback,
482   FLAC__StreamDecoderMetadataCallback metadata_callback,
483   FLAC__StreamDecoderErrorCallback error_callback,
484   void *client_data
485)
486{
487   return init_stream_internal_(
488      decoder,
489      read_callback,
490      seek_callback,
491      tell_callback,
492      length_callback,
493      eof_callback,
494      write_callback,
495      metadata_callback,
496      error_callback,
497      client_data,
498      /*is_ogg=*/false
499   );
500}
501
502FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
503   FLAC__StreamDecoder *decoder,
504   FLAC__StreamDecoderReadCallback read_callback,
505   FLAC__StreamDecoderSeekCallback seek_callback,
506   FLAC__StreamDecoderTellCallback tell_callback,
507   FLAC__StreamDecoderLengthCallback length_callback,
508   FLAC__StreamDecoderEofCallback eof_callback,
509   FLAC__StreamDecoderWriteCallback write_callback,
510   FLAC__StreamDecoderMetadataCallback metadata_callback,
511   FLAC__StreamDecoderErrorCallback error_callback,
512   void *client_data
513)
514{
515   return init_stream_internal_(
516      decoder,
517      read_callback,
518      seek_callback,
519      tell_callback,
520      length_callback,
521      eof_callback,
522      write_callback,
523      metadata_callback,
524      error_callback,
525      client_data,
526      /*is_ogg=*/true
527   );
528}
529
530static FLAC__StreamDecoderInitStatus init_FILE_internal_(
531   FLAC__StreamDecoder *decoder,
532   FILE *file,
533   FLAC__StreamDecoderWriteCallback write_callback,
534   FLAC__StreamDecoderMetadataCallback metadata_callback,
535   FLAC__StreamDecoderErrorCallback error_callback,
536   void *client_data,
537   FLAC__bool is_ogg
538)
539{
540   FLAC__ASSERT(0 != decoder);
541   FLAC__ASSERT(0 != file);
542
543   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
544      return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
545
546   if(0 == write_callback || 0 == error_callback)
547      return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
548
549   /*
550    * To make sure that our file does not go unclosed after an error, we
551    * must assign the FILE pointer before any further error can occur in
552    * this routine.
553    */
554   if(file == stdin)
555      file = get_binary_stdin_(); /* just to be safe */
556
557   decoder->private_->file = file;
558
559   return init_stream_internal_(
560      decoder,
561      file_read_callback_,
562      decoder->private_->file == stdin? 0: file_seek_callback_,
563      decoder->private_->file == stdin? 0: file_tell_callback_,
564      decoder->private_->file == stdin? 0: file_length_callback_,
565      file_eof_callback_,
566      write_callback,
567      metadata_callback,
568      error_callback,
569      client_data,
570      is_ogg
571   );
572}
573
574FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
575   FLAC__StreamDecoder *decoder,
576   FILE *file,
577   FLAC__StreamDecoderWriteCallback write_callback,
578   FLAC__StreamDecoderMetadataCallback metadata_callback,
579   FLAC__StreamDecoderErrorCallback error_callback,
580   void *client_data
581)
582{
583   return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
584}
585
586FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
587   FLAC__StreamDecoder *decoder,
588   FILE *file,
589   FLAC__StreamDecoderWriteCallback write_callback,
590   FLAC__StreamDecoderMetadataCallback metadata_callback,
591   FLAC__StreamDecoderErrorCallback error_callback,
592   void *client_data
593)
594{
595   return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
596}
597
598static FLAC__StreamDecoderInitStatus init_file_internal_(
599   FLAC__StreamDecoder *decoder,
600   const char *filename,
601   FLAC__StreamDecoderWriteCallback write_callback,
602   FLAC__StreamDecoderMetadataCallback metadata_callback,
603   FLAC__StreamDecoderErrorCallback error_callback,
604   void *client_data,
605   FLAC__bool is_ogg
606)
607{
608   FILE *file;
609
610   FLAC__ASSERT(0 != decoder);
611
612   /*
613    * To make sure that our file does not go unclosed after an error, we
614    * have to do the same entrance checks here that are later performed
615    * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
616    */
617   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
618      return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
619
620   if(0 == write_callback || 0 == error_callback)
621      return decoder->protected_->state = FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
622
623   file = filename? fopen(filename, "rb") : stdin;
624
625   if(0 == file)
626      return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
627
628   return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
629}
630
631FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
632   FLAC__StreamDecoder *decoder,
633   const char *filename,
634   FLAC__StreamDecoderWriteCallback write_callback,
635   FLAC__StreamDecoderMetadataCallback metadata_callback,
636   FLAC__StreamDecoderErrorCallback error_callback,
637   void *client_data
638)
639{
640   return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
641}
642
643FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
644   FLAC__StreamDecoder *decoder,
645   const char *filename,
646   FLAC__StreamDecoderWriteCallback write_callback,
647   FLAC__StreamDecoderMetadataCallback metadata_callback,
648   FLAC__StreamDecoderErrorCallback error_callback,
649   void *client_data
650)
651{
652   return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
653}
654
655FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
656{
657   FLAC__bool md5_failed = false;
658   unsigned i;
659
660   FLAC__ASSERT(0 != decoder);
661   FLAC__ASSERT(0 != decoder->private_);
662   FLAC__ASSERT(0 != decoder->protected_);
663
664   if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
665      return true;
666
667   /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
668    * always call FLAC__MD5Final()
669    */
670   FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
671
672   if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
673      free(decoder->private_->seek_table.data.seek_table.points);
674      decoder->private_->seek_table.data.seek_table.points = 0;
675      decoder->private_->has_seek_table = false;
676   }
677   FLAC__bitreader_free(decoder->private_->input);
678   for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
679      /* WATCHOUT:
680       * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
681       * output arrays have a buffer of up to 3 zeroes in front
682       * (at negative indices) for alignment purposes; we use 4
683       * to keep the data well-aligned.
684       */
685      if(0 != decoder->private_->output[i]) {
686         free(decoder->private_->output[i]-4);
687         decoder->private_->output[i] = 0;
688      }
689      if(0 != decoder->private_->residual_unaligned[i]) {
690         free(decoder->private_->residual_unaligned[i]);
691         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
692      }
693   }
694   decoder->private_->output_capacity = 0;
695   decoder->private_->output_channels = 0;
696
697#if FLAC__HAS_OGG
698   if(decoder->private_->is_ogg)
699      FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
700#endif
701
702   if(0 != decoder->private_->file) {
703      if(decoder->private_->file != stdin)
704         fclose(decoder->private_->file);
705      decoder->private_->file = 0;
706   }
707
708   if(decoder->private_->do_md5_checking) {
709      if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
710         md5_failed = true;
711   }
712   decoder->private_->is_seeking = false;
713
714   set_defaults_(decoder);
715
716   decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
717
718   return !md5_failed;
719}
720
721FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
722{
723   FLAC__ASSERT(0 != decoder);
724   FLAC__ASSERT(0 != decoder->private_);
725   FLAC__ASSERT(0 != decoder->protected_);
726   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
727      return false;
728#if FLAC__HAS_OGG
729   /* can't check decoder->private_->is_ogg since that's not set until init time */
730   FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
731   return true;
732#else
733   (void)value;
734   return false;
735#endif
736}
737
738FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
739{
740   FLAC__ASSERT(0 != decoder);
741   FLAC__ASSERT(0 != decoder->protected_);
742   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
743      return false;
744   decoder->protected_->md5_checking = value;
745   return true;
746}
747
748FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
749{
750   FLAC__ASSERT(0 != decoder);
751   FLAC__ASSERT(0 != decoder->private_);
752   FLAC__ASSERT(0 != decoder->protected_);
753   FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
754   /* double protection */
755   if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
756      return false;
757   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
758      return false;
759   decoder->private_->metadata_filter[type] = true;
760   if(type == FLAC__METADATA_TYPE_APPLICATION)
761      decoder->private_->metadata_filter_ids_count = 0;
762   return true;
763}
764
765FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
766{
767   FLAC__ASSERT(0 != decoder);
768   FLAC__ASSERT(0 != decoder->private_);
769   FLAC__ASSERT(0 != decoder->protected_);
770   FLAC__ASSERT(0 != id);
771   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
772      return false;
773
774   if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
775      return true;
776
777   FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
778
779   if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
780      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))) {
781         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
782         return false;
783      }
784      decoder->private_->metadata_filter_ids_capacity *= 2;
785   }
786
787   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));
788   decoder->private_->metadata_filter_ids_count++;
789
790   return true;
791}
792
793FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
794{
795   unsigned i;
796   FLAC__ASSERT(0 != decoder);
797   FLAC__ASSERT(0 != decoder->private_);
798   FLAC__ASSERT(0 != decoder->protected_);
799   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
800      return false;
801   for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
802      decoder->private_->metadata_filter[i] = true;
803   decoder->private_->metadata_filter_ids_count = 0;
804   return true;
805}
806
807FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
808{
809   FLAC__ASSERT(0 != decoder);
810   FLAC__ASSERT(0 != decoder->private_);
811   FLAC__ASSERT(0 != decoder->protected_);
812   FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
813   /* double protection */
814   if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
815      return false;
816   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
817      return false;
818   decoder->private_->metadata_filter[type] = false;
819   if(type == FLAC__METADATA_TYPE_APPLICATION)
820      decoder->private_->metadata_filter_ids_count = 0;
821   return true;
822}
823
824FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
825{
826   FLAC__ASSERT(0 != decoder);
827   FLAC__ASSERT(0 != decoder->private_);
828   FLAC__ASSERT(0 != decoder->protected_);
829   FLAC__ASSERT(0 != id);
830   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
831      return false;
832
833   if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
834      return true;
835
836   FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
837
838   if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
839      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))) {
840         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
841         return false;
842      }
843      decoder->private_->metadata_filter_ids_capacity *= 2;
844   }
845
846   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));
847   decoder->private_->metadata_filter_ids_count++;
848
849   return true;
850}
851
852FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
853{
854   FLAC__ASSERT(0 != decoder);
855   FLAC__ASSERT(0 != decoder->private_);
856   FLAC__ASSERT(0 != decoder->protected_);
857   if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
858      return false;
859   memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
860   decoder->private_->metadata_filter_ids_count = 0;
861   return true;
862}
863
864FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
865{
866   FLAC__ASSERT(0 != decoder);
867   FLAC__ASSERT(0 != decoder->protected_);
868   return decoder->protected_->state;
869}
870
871FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
872{
873   return FLAC__StreamDecoderStateString[decoder->protected_->state];
874}
875
876FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
877{
878   FLAC__ASSERT(0 != decoder);
879   FLAC__ASSERT(0 != decoder->protected_);
880   return decoder->protected_->md5_checking;
881}
882
883FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
884{
885   FLAC__ASSERT(0 != decoder);
886   FLAC__ASSERT(0 != decoder->protected_);
887   return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
888}
889
890FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
891{
892   FLAC__ASSERT(0 != decoder);
893   FLAC__ASSERT(0 != decoder->protected_);
894   return decoder->protected_->channels;
895}
896
897FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
898{
899   FLAC__ASSERT(0 != decoder);
900   FLAC__ASSERT(0 != decoder->protected_);
901   return decoder->protected_->channel_assignment;
902}
903
904FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
905{
906   FLAC__ASSERT(0 != decoder);
907   FLAC__ASSERT(0 != decoder->protected_);
908   return decoder->protected_->bits_per_sample;
909}
910
911FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
912{
913   FLAC__ASSERT(0 != decoder);
914   FLAC__ASSERT(0 != decoder->protected_);
915   return decoder->protected_->sample_rate;
916}
917
918FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
919{
920   FLAC__ASSERT(0 != decoder);
921   FLAC__ASSERT(0 != decoder->protected_);
922   return decoder->protected_->blocksize;
923}
924
925FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
926{
927   FLAC__ASSERT(0 != decoder);
928   FLAC__ASSERT(0 != decoder->private_);
929   FLAC__ASSERT(0 != position);
930
931#if FLAC__HAS_OGG
932   if(decoder->private_->is_ogg)
933      return false;
934#endif
935   if(0 == decoder->private_->tell_callback)
936      return false;
937   if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
938      return false;
939   /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
940   if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
941      return false;
942   FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
943   *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
944   return true;
945}
946
947FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
948{
949   FLAC__ASSERT(0 != decoder);
950   FLAC__ASSERT(0 != decoder->private_);
951   FLAC__ASSERT(0 != decoder->protected_);
952
953   decoder->private_->samples_decoded = 0;
954   decoder->private_->do_md5_checking = false;
955
956#if FLAC__HAS_OGG
957   if(decoder->private_->is_ogg)
958      FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
959#endif
960
961   if(!FLAC__bitreader_clear(decoder->private_->input)) {
962      decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
963      return false;
964   }
965   decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
966
967   return true;
968}
969
970FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
971{
972   FLAC__ASSERT(0 != decoder);
973   FLAC__ASSERT(0 != decoder->private_);
974   FLAC__ASSERT(0 != decoder->protected_);
975
976   if(!FLAC__stream_decoder_flush(decoder)) {
977      /* above call sets the state for us */
978      return false;
979   }
980
981#if FLAC__HAS_OGG
982   /*@@@ could go in !internal_reset_hack block below */
983   if(decoder->private_->is_ogg)
984      FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
985#endif
986
987   /* Rewind if necessary.  If FLAC__stream_decoder_init() is calling us,
988    * (internal_reset_hack) don't try to rewind since we are already at
989    * the beginning of the stream and don't want to fail if the input is
990    * not seekable.
991    */
992   if(!decoder->private_->internal_reset_hack) {
993      if(decoder->private_->file == stdin)
994         return false; /* can't rewind stdin, reset fails */
995      if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
996         return false; /* seekable and seek fails, reset fails */
997   }
998   else
999      decoder->private_->internal_reset_hack = false;
1000
1001   decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
1002
1003   decoder->private_->has_stream_info = false;
1004   if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
1005      free(decoder->private_->seek_table.data.seek_table.points);
1006      decoder->private_->seek_table.data.seek_table.points = 0;
1007      decoder->private_->has_seek_table = false;
1008   }
1009   decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
1010   /*
1011    * This goes in reset() and not flush() because according to the spec, a
1012    * fixed-blocksize stream must stay that way through the whole stream.
1013    */
1014   decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
1015
1016   /* We initialize the FLAC__MD5Context even though we may never use it.  This
1017    * is because md5 checking may be turned on to start and then turned off if
1018    * a seek occurs.  So we init the context here and finalize it in
1019    * FLAC__stream_decoder_finish() to make sure things are always cleaned up
1020    * properly.
1021    */
1022   FLAC__MD5Init(&decoder->private_->md5context);
1023
1024   decoder->private_->first_frame_offset = 0;
1025   decoder->private_->unparseable_frame_count = 0;
1026
1027   return true;
1028}
1029
1030FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
1031{
1032   FLAC__bool got_a_frame;
1033   FLAC__ASSERT(0 != decoder);
1034   FLAC__ASSERT(0 != decoder->protected_);
1035
1036   while(1) {
1037      switch(decoder->protected_->state) {
1038         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1039            if(!find_metadata_(decoder))
1040               return false; /* above function sets the status for us */
1041            break;
1042         case FLAC__STREAM_DECODER_READ_METADATA:
1043            if(!read_metadata_(decoder))
1044               return false; /* above function sets the status for us */
1045            else
1046               return true;
1047         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1048            if(!frame_sync_(decoder))
1049               return true; /* above function sets the status for us */
1050            break;
1051         case FLAC__STREAM_DECODER_READ_FRAME:
1052            if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
1053               return false; /* above function sets the status for us */
1054            if(got_a_frame)
1055               return true; /* above function sets the status for us */
1056            break;
1057         case FLAC__STREAM_DECODER_END_OF_STREAM:
1058         case FLAC__STREAM_DECODER_ABORTED:
1059            return true;
1060         default:
1061            FLAC__ASSERT(0);
1062            return false;
1063      }
1064   }
1065}
1066
1067FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
1068{
1069   FLAC__ASSERT(0 != decoder);
1070   FLAC__ASSERT(0 != decoder->protected_);
1071
1072   while(1) {
1073      switch(decoder->protected_->state) {
1074         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1075            if(!find_metadata_(decoder))
1076               return false; /* above function sets the status for us */
1077            break;
1078         case FLAC__STREAM_DECODER_READ_METADATA:
1079            if(!read_metadata_(decoder))
1080               return false; /* above function sets the status for us */
1081            break;
1082         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1083         case FLAC__STREAM_DECODER_READ_FRAME:
1084         case FLAC__STREAM_DECODER_END_OF_STREAM:
1085         case FLAC__STREAM_DECODER_ABORTED:
1086            return true;
1087         default:
1088            FLAC__ASSERT(0);
1089            return false;
1090      }
1091   }
1092}
1093
1094FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
1095{
1096   FLAC__bool dummy;
1097   FLAC__ASSERT(0 != decoder);
1098   FLAC__ASSERT(0 != decoder->protected_);
1099
1100   while(1) {
1101      switch(decoder->protected_->state) {
1102         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1103            if(!find_metadata_(decoder))
1104               return false; /* above function sets the status for us */
1105            break;
1106         case FLAC__STREAM_DECODER_READ_METADATA:
1107            if(!read_metadata_(decoder))
1108               return false; /* above function sets the status for us */
1109            break;
1110         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1111            if(!frame_sync_(decoder))
1112               return true; /* above function sets the status for us */
1113            break;
1114         case FLAC__STREAM_DECODER_READ_FRAME:
1115            if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
1116               return false; /* above function sets the status for us */
1117            break;
1118         case FLAC__STREAM_DECODER_END_OF_STREAM:
1119         case FLAC__STREAM_DECODER_ABORTED:
1120            return true;
1121         default:
1122            FLAC__ASSERT(0);
1123            return false;
1124      }
1125   }
1126}
1127
1128FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
1129{
1130   FLAC__bool got_a_frame;
1131   FLAC__ASSERT(0 != decoder);
1132   FLAC__ASSERT(0 != decoder->protected_);
1133
1134   while(1) {
1135      switch(decoder->protected_->state) {
1136         case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
1137         case FLAC__STREAM_DECODER_READ_METADATA:
1138            return false; /* above function sets the status for us */
1139         case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
1140            if(!frame_sync_(decoder))
1141               return true; /* above function sets the status for us */
1142            break;
1143         case FLAC__STREAM_DECODER_READ_FRAME:
1144            if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
1145               return false; /* above function sets the status for us */
1146            if(got_a_frame)
1147               return true; /* above function sets the status for us */
1148            break;
1149         case FLAC__STREAM_DECODER_END_OF_STREAM:
1150         case FLAC__STREAM_DECODER_ABORTED:
1151            return true;
1152         default:
1153            FLAC__ASSERT(0);
1154            return false;
1155      }
1156   }
1157}
1158
1159FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
1160{
1161   FLAC__uint64 length;
1162
1163   FLAC__ASSERT(0 != decoder);
1164
1165   if(
1166      decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
1167      decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
1168      decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
1169      decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
1170      decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
1171   )
1172      return false;
1173
1174   if(0 == decoder->private_->seek_callback)
1175      return false;
1176
1177   FLAC__ASSERT(decoder->private_->seek_callback);
1178   FLAC__ASSERT(decoder->private_->tell_callback);
1179   FLAC__ASSERT(decoder->private_->length_callback);
1180   FLAC__ASSERT(decoder->private_->eof_callback);
1181
1182   if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
1183      return false;
1184
1185   decoder->private_->is_seeking = true;
1186
1187   /* turn off md5 checking if a seek is attempted */
1188   decoder->private_->do_md5_checking = false;
1189
1190   /* 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) */
1191   if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
1192      decoder->private_->is_seeking = false;
1193      return false;
1194   }
1195
1196   /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
1197   if(
1198      decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
1199      decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
1200   ) {
1201      if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
1202         /* above call sets the state for us */
1203         decoder->private_->is_seeking = false;
1204         return false;
1205      }
1206      /* check this again in case we didn't know total_samples the first time */
1207      if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
1208         decoder->private_->is_seeking = false;
1209         return false;
1210      }
1211   }
1212
1213   {
1214      const FLAC__bool ok =
1215#if FLAC__HAS_OGG
1216         decoder->private_->is_ogg?
1217         seek_to_absolute_sample_ogg_(decoder, length, sample) :
1218#endif
1219         seek_to_absolute_sample_(decoder, length, sample)
1220      ;
1221      decoder->private_->is_seeking = false;
1222      return ok;
1223   }
1224}
1225
1226/***********************************************************************
1227 *
1228 * Protected class methods
1229 *
1230 ***********************************************************************/
1231
1232unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
1233{
1234   FLAC__ASSERT(0 != decoder);
1235   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1236   FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
1237   return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
1238}
1239
1240/***********************************************************************
1241 *
1242 * Private class methods
1243 *
1244 ***********************************************************************/
1245
1246void set_defaults_(FLAC__StreamDecoder *decoder)
1247{
1248#if FLAC__HAS_OGG
1249   decoder->private_->is_ogg = false;
1250#endif
1251   decoder->private_->read_callback = 0;
1252   decoder->private_->seek_callback = 0;
1253   decoder->private_->tell_callback = 0;
1254   decoder->private_->length_callback = 0;
1255   decoder->private_->eof_callback = 0;
1256   decoder->private_->write_callback = 0;
1257   decoder->private_->metadata_callback = 0;
1258   decoder->private_->error_callback = 0;
1259   decoder->private_->client_data = 0;
1260
1261   memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
1262   decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
1263   decoder->private_->metadata_filter_ids_count = 0;
1264
1265   decoder->protected_->md5_checking = false;
1266
1267#if FLAC__HAS_OGG
1268   FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
1269#endif
1270}
1271
1272/*
1273 * This will forcibly set stdin to binary mode (for OSes that require it)
1274 */
1275FILE *get_binary_stdin_(void)
1276{
1277    #if 0
1278   /* if something breaks here it is probably due to the presence or
1279    * absence of an underscore before the identifiers 'setmode',
1280    * 'fileno', and/or 'O_BINARY'; check your system header files.
1281    */
1282#if defined _MSC_VER || defined __MINGW32__
1283   _setmode(_fileno(stdin), _O_BINARY);
1284#elif defined __CYGWIN__
1285   /* almost certainly not needed for any modern Cygwin, but let's be safe... */
1286   setmode(_fileno(stdin), _O_BINARY);
1287#elif defined __EMX__
1288   setmode(fileno(stdin), O_BINARY);
1289#endif
1290    #endif
1291   return stdin;
1292}
1293
1294FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
1295{
1296   unsigned i;
1297   FLAC__int32 *tmp;
1298
1299   if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
1300      return true;
1301
1302   /* simply using realloc() is not practical because the number of channels may change mid-stream */
1303
1304   for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
1305      if(0 != decoder->private_->output[i]) {
1306         free(decoder->private_->output[i]-4);
1307         decoder->private_->output[i] = 0;
1308      }
1309      if(0 != decoder->private_->residual_unaligned[i]) {
1310         free(decoder->private_->residual_unaligned[i]);
1311         decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
1312      }
1313   }
1314
1315   for(i = 0; i < channels; i++) {
1316      /* WATCHOUT:
1317       * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
1318       * output arrays have a buffer of up to 3 zeroes in front
1319       * (at negative indices) for alignment purposes; we use 4
1320       * to keep the data well-aligned.
1321       */
1322      tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
1323      if(tmp == 0) {
1324         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1325         return false;
1326      }
1327      memset(tmp, 0, sizeof(FLAC__int32)*4);
1328      decoder->private_->output[i] = tmp + 4;
1329
1330      /* WATCHOUT:
1331       * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
1332       */
1333      if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
1334         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1335         return false;
1336      }
1337   }
1338
1339   decoder->private_->output_capacity = size;
1340   decoder->private_->output_channels = channels;
1341
1342   return true;
1343}
1344
1345FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
1346{
1347   size_t i;
1348
1349   FLAC__ASSERT(0 != decoder);
1350   FLAC__ASSERT(0 != decoder->private_);
1351
1352   for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
1353      if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
1354         return true;
1355
1356   return false;
1357}
1358
1359FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
1360{
1361   FLAC__uint32 x;
1362   unsigned i, id;
1363   FLAC__bool first = true;
1364
1365   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1366
1367   for(i = id = 0; i < 4; ) {
1368      if(decoder->private_->cached) {
1369         x = (FLAC__uint32)decoder->private_->lookahead;
1370         decoder->private_->cached = false;
1371      }
1372      else {
1373         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1374            return false; /* read_callback_ sets the state for us */
1375      }
1376      if(x == FLAC__STREAM_SYNC_STRING[i]) {
1377         first = true;
1378         i++;
1379         id = 0;
1380         continue;
1381      }
1382      if(x == ID3V2_TAG_[id]) {
1383         id++;
1384         i = 0;
1385         if(id == 3) {
1386            if(!skip_id3v2_tag_(decoder))
1387               return false; /* skip_id3v2_tag_ sets the state for us */
1388         }
1389         continue;
1390      }
1391      id = 0;
1392      if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1393         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1394         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1395            return false; /* read_callback_ sets the state for us */
1396
1397         /* 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 */
1398         /* else we have to check if the second byte is the end of a sync code */
1399         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1400            decoder->private_->lookahead = (FLAC__byte)x;
1401            decoder->private_->cached = true;
1402         }
1403         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1404            decoder->private_->header_warmup[1] = (FLAC__byte)x;
1405            decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1406            return true;
1407         }
1408      }
1409      i = 0;
1410      if(first) {
1411         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1412         first = false;
1413      }
1414   }
1415
1416   decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
1417   return true;
1418}
1419
1420FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
1421{
1422   FLAC__bool is_last;
1423   FLAC__uint32 i, x, type, length;
1424
1425   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1426
1427   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
1428      return false; /* read_callback_ sets the state for us */
1429   is_last = x? true : false;
1430
1431   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
1432      return false; /* read_callback_ sets the state for us */
1433
1434   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
1435      return false; /* read_callback_ sets the state for us */
1436
1437   if(type == FLAC__METADATA_TYPE_STREAMINFO) {
1438      if(!read_metadata_streaminfo_(decoder, is_last, length))
1439         return false;
1440
1441      decoder->private_->has_stream_info = true;
1442      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))
1443         decoder->private_->do_md5_checking = false;
1444      if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
1445         decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
1446   }
1447   else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
1448      if(!read_metadata_seektable_(decoder, is_last, length))
1449         return false;
1450
1451      decoder->private_->has_seek_table = true;
1452      if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
1453         decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
1454   }
1455   else {
1456      FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
1457      unsigned real_length = length;
1458      FLAC__StreamMetadata block;
1459
1460      block.is_last = is_last;
1461      block.type = (FLAC__MetadataType)type;
1462      block.length = length;
1463
1464      if(type == FLAC__METADATA_TYPE_APPLICATION) {
1465         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
1466            return false; /* read_callback_ sets the state for us */
1467
1468         if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
1469            decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
1470            return false;
1471         }
1472
1473         real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
1474
1475         if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
1476            skip_it = !skip_it;
1477      }
1478
1479      if(skip_it) {
1480         if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1481            return false; /* read_callback_ sets the state for us */
1482      }
1483      else {
1484         switch(type) {
1485            case FLAC__METADATA_TYPE_PADDING:
1486               /* skip the padding bytes */
1487               if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
1488                  return false; /* read_callback_ sets the state for us */
1489               break;
1490            case FLAC__METADATA_TYPE_APPLICATION:
1491               /* remember, we read the ID already */
1492               if(real_length > 0) {
1493                  if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
1494                     decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1495                     return false;
1496                  }
1497                  if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
1498                     return false; /* read_callback_ sets the state for us */
1499               }
1500               else
1501                  block.data.application.data = 0;
1502               break;
1503            case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1504               if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
1505                  return false;
1506               break;
1507            case FLAC__METADATA_TYPE_CUESHEET:
1508               if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
1509                  return false;
1510               break;
1511            case FLAC__METADATA_TYPE_PICTURE:
1512               if(!read_metadata_picture_(decoder, &block.data.picture))
1513                  return false;
1514               break;
1515            case FLAC__METADATA_TYPE_STREAMINFO:
1516            case FLAC__METADATA_TYPE_SEEKTABLE:
1517               FLAC__ASSERT(0);
1518               break;
1519            default:
1520               if(real_length > 0) {
1521                  if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
1522                     decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1523                     return false;
1524                  }
1525                  if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
1526                     return false; /* read_callback_ sets the state for us */
1527               }
1528               else
1529                  block.data.unknown.data = 0;
1530               break;
1531         }
1532         if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
1533            decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
1534
1535         /* now we have to free any malloc()ed data in the block */
1536         switch(type) {
1537            case FLAC__METADATA_TYPE_PADDING:
1538               break;
1539            case FLAC__METADATA_TYPE_APPLICATION:
1540               if(0 != block.data.application.data)
1541                  free(block.data.application.data);
1542               break;
1543            case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1544               if(0 != block.data.vorbis_comment.vendor_string.entry)
1545                  free(block.data.vorbis_comment.vendor_string.entry);
1546               if(block.data.vorbis_comment.num_comments > 0)
1547                  for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
1548                     if(0 != block.data.vorbis_comment.comments[i].entry)
1549                        free(block.data.vorbis_comment.comments[i].entry);
1550               if(0 != block.data.vorbis_comment.comments)
1551                  free(block.data.vorbis_comment.comments);
1552               break;
1553            case FLAC__METADATA_TYPE_CUESHEET:
1554               if(block.data.cue_sheet.num_tracks > 0)
1555                  for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
1556                     if(0 != block.data.cue_sheet.tracks[i].indices)
1557                        free(block.data.cue_sheet.tracks[i].indices);
1558               if(0 != block.data.cue_sheet.tracks)
1559                  free(block.data.cue_sheet.tracks);
1560               break;
1561            case FLAC__METADATA_TYPE_PICTURE:
1562               if(0 != block.data.picture.mime_type)
1563                  free(block.data.picture.mime_type);
1564               if(0 != block.data.picture.description)
1565                  free(block.data.picture.description);
1566               if(0 != block.data.picture.data)
1567                  free(block.data.picture.data);
1568               break;
1569            case FLAC__METADATA_TYPE_STREAMINFO:
1570            case FLAC__METADATA_TYPE_SEEKTABLE:
1571               FLAC__ASSERT(0);
1572            default:
1573               if(0 != block.data.unknown.data)
1574                  free(block.data.unknown.data);
1575               break;
1576         }
1577      }
1578   }
1579
1580   if(is_last) {
1581      /* if this fails, it's OK, it's just a hint for the seek routine */
1582      if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
1583         decoder->private_->first_frame_offset = 0;
1584      decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
1585   }
1586
1587   return true;
1588}
1589
1590FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1591{
1592   FLAC__uint32 x;
1593   unsigned bits, used_bits = 0;
1594
1595   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1596
1597   decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
1598   decoder->private_->stream_info.is_last = is_last;
1599   decoder->private_->stream_info.length = length;
1600
1601   bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
1602   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
1603      return false; /* read_callback_ sets the state for us */
1604   decoder->private_->stream_info.data.stream_info.min_blocksize = x;
1605   used_bits += bits;
1606
1607   bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
1608   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
1609      return false; /* read_callback_ sets the state for us */
1610   decoder->private_->stream_info.data.stream_info.max_blocksize = x;
1611   used_bits += bits;
1612
1613   bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
1614   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
1615      return false; /* read_callback_ sets the state for us */
1616   decoder->private_->stream_info.data.stream_info.min_framesize = x;
1617   used_bits += bits;
1618
1619   bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
1620   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
1621      return false; /* read_callback_ sets the state for us */
1622   decoder->private_->stream_info.data.stream_info.max_framesize = x;
1623   used_bits += bits;
1624
1625   bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
1626   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
1627      return false; /* read_callback_ sets the state for us */
1628   decoder->private_->stream_info.data.stream_info.sample_rate = x;
1629   used_bits += bits;
1630
1631   bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
1632   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
1633      return false; /* read_callback_ sets the state for us */
1634   decoder->private_->stream_info.data.stream_info.channels = x+1;
1635   used_bits += bits;
1636
1637   bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
1638   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
1639      return false; /* read_callback_ sets the state for us */
1640   decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
1641   used_bits += bits;
1642
1643   bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
1644   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))
1645      return false; /* read_callback_ sets the state for us */
1646   used_bits += bits;
1647
1648   if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
1649      return false; /* read_callback_ sets the state for us */
1650   used_bits += 16*8;
1651
1652   /* skip the rest of the block */
1653   FLAC__ASSERT(used_bits % 8 == 0);
1654   length -= (used_bits / 8);
1655   if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1656      return false; /* read_callback_ sets the state for us */
1657
1658   return true;
1659}
1660
1661FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
1662{
1663   FLAC__uint32 i, x;
1664   FLAC__uint64 xx;
1665
1666   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1667
1668   decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
1669   decoder->private_->seek_table.is_last = is_last;
1670   decoder->private_->seek_table.length = length;
1671
1672   decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1673
1674   /* use realloc since we may pass through here several times (e.g. after seeking) */
1675   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)))) {
1676      decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1677      return false;
1678   }
1679   for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
1680      if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
1681         return false; /* read_callback_ sets the state for us */
1682      decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
1683
1684      if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
1685         return false; /* read_callback_ sets the state for us */
1686      decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
1687
1688      if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
1689         return false; /* read_callback_ sets the state for us */
1690      decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
1691   }
1692   length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
1693   /* if there is a partial point left, skip over it */
1694   if(length > 0) {
1695      /*@@@ do a send_error_to_client_() here?  there's an argument for either way */
1696      if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
1697         return false; /* read_callback_ sets the state for us */
1698   }
1699
1700   return true;
1701}
1702
1703FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
1704{
1705   FLAC__uint32 i;
1706
1707   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1708
1709   /* read vendor string */
1710   FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1711   if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
1712      return false; /* read_callback_ sets the state for us */
1713   if(obj->vendor_string.length > 0) {
1714      if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
1715         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1716         return false;
1717      }
1718      if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
1719         return false; /* read_callback_ sets the state for us */
1720      obj->vendor_string.entry[obj->vendor_string.length] = '\0';
1721   }
1722   else
1723      obj->vendor_string.entry = 0;
1724
1725   /* read num comments */
1726   FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
1727   if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
1728      return false; /* read_callback_ sets the state for us */
1729
1730   /* read comments */
1731   if(obj->num_comments > 0) {
1732      if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
1733         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1734         return false;
1735      }
1736      for(i = 0; i < obj->num_comments; i++) {
1737         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
1738         if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
1739            return false; /* read_callback_ sets the state for us */
1740         if(obj->comments[i].length > 0) {
1741            if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
1742               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1743               return false;
1744            }
1745            if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
1746               return false; /* read_callback_ sets the state for us */
1747            obj->comments[i].entry[obj->comments[i].length] = '\0';
1748         }
1749         else
1750            obj->comments[i].entry = 0;
1751      }
1752   }
1753   else {
1754      obj->comments = 0;
1755   }
1756
1757   return true;
1758}
1759
1760FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
1761{
1762   FLAC__uint32 i, j, x;
1763
1764   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1765
1766   memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
1767
1768   FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
1769   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))
1770      return false; /* read_callback_ sets the state for us */
1771
1772   if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
1773      return false; /* read_callback_ sets the state for us */
1774
1775   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
1776      return false; /* read_callback_ sets the state for us */
1777   obj->is_cd = x? true : false;
1778
1779   if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
1780      return false; /* read_callback_ sets the state for us */
1781
1782   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
1783      return false; /* read_callback_ sets the state for us */
1784   obj->num_tracks = x;
1785
1786   if(obj->num_tracks > 0) {
1787      if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
1788         decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1789         return false;
1790      }
1791      for(i = 0; i < obj->num_tracks; i++) {
1792         FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
1793         if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
1794            return false; /* read_callback_ sets the state for us */
1795
1796         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
1797            return false; /* read_callback_ sets the state for us */
1798         track->number = (FLAC__byte)x;
1799
1800         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
1801         if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
1802            return false; /* read_callback_ sets the state for us */
1803
1804         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
1805            return false; /* read_callback_ sets the state for us */
1806         track->type = x;
1807
1808         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
1809            return false; /* read_callback_ sets the state for us */
1810         track->pre_emphasis = x;
1811
1812         if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
1813            return false; /* read_callback_ sets the state for us */
1814
1815         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
1816            return false; /* read_callback_ sets the state for us */
1817         track->num_indices = (FLAC__byte)x;
1818
1819         if(track->num_indices > 0) {
1820            if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
1821               decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1822               return false;
1823            }
1824            for(j = 0; j < track->num_indices; j++) {
1825               FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
1826               if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
1827                  return false; /* read_callback_ sets the state for us */
1828
1829               if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
1830                  return false; /* read_callback_ sets the state for us */
1831               index->number = (FLAC__byte)x;
1832
1833               if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
1834                  return false; /* read_callback_ sets the state for us */
1835            }
1836         }
1837      }
1838   }
1839
1840   return true;
1841}
1842
1843FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
1844{
1845   FLAC__uint32 x;
1846
1847   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
1848
1849   /* read type */
1850   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
1851      return false; /* read_callback_ sets the state for us */
1852   obj->type = x;
1853
1854   /* read MIME type */
1855   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
1856      return false; /* read_callback_ sets the state for us */
1857   if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
1858      decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1859      return false;
1860   }
1861   if(x > 0) {
1862      if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
1863         return false; /* read_callback_ sets the state for us */
1864   }
1865   obj->mime_type[x] = '\0';
1866
1867   /* read description */
1868   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
1869      return false; /* read_callback_ sets the state for us */
1870   if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
1871      decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1872      return false;
1873   }
1874   if(x > 0) {
1875      if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
1876         return false; /* read_callback_ sets the state for us */
1877   }
1878   obj->description[x] = '\0';
1879
1880   /* read width */
1881   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
1882      return false; /* read_callback_ sets the state for us */
1883
1884   /* read height */
1885   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
1886      return false; /* read_callback_ sets the state for us */
1887
1888   /* read depth */
1889   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
1890      return false; /* read_callback_ sets the state for us */
1891
1892   /* read colors */
1893   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
1894      return false; /* read_callback_ sets the state for us */
1895
1896   /* read data */
1897   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
1898      return false; /* read_callback_ sets the state for us */
1899   if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
1900      decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
1901      return false;
1902   }
1903   if(obj->data_length > 0) {
1904      if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
1905         return false; /* read_callback_ sets the state for us */
1906   }
1907
1908   return true;
1909}
1910
1911FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
1912{
1913   FLAC__uint32 x;
1914   unsigned i, skip;
1915
1916   /* skip the version and flags bytes */
1917   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
1918      return false; /* read_callback_ sets the state for us */
1919   /* get the size (in bytes) to skip */
1920   skip = 0;
1921   for(i = 0; i < 4; i++) {
1922      if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1923         return false; /* read_callback_ sets the state for us */
1924      skip <<= 7;
1925      skip |= (x & 0x7f);
1926   }
1927   /* skip the rest of the tag */
1928   if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
1929      return false; /* read_callback_ sets the state for us */
1930   return true;
1931}
1932
1933FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
1934{
1935   FLAC__uint32 x;
1936   FLAC__bool first = true;
1937
1938   /* If we know the total number of samples in the stream, stop if we've read that many. */
1939   /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
1940   if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
1941      if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
1942         decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
1943         return true;
1944      }
1945   }
1946
1947   /* make sure we're byte aligned */
1948   if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
1949      if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
1950         return false; /* read_callback_ sets the state for us */
1951   }
1952
1953   while(1) {
1954      if(decoder->private_->cached) {
1955         x = (FLAC__uint32)decoder->private_->lookahead;
1956         decoder->private_->cached = false;
1957      }
1958      else {
1959         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1960            return false; /* read_callback_ sets the state for us */
1961      }
1962      if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1963         decoder->private_->header_warmup[0] = (FLAC__byte)x;
1964         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
1965            return false; /* read_callback_ sets the state for us */
1966
1967         /* 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 */
1968         /* else we have to check if the second byte is the end of a sync code */
1969         if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
1970            decoder->private_->lookahead = (FLAC__byte)x;
1971            decoder->private_->cached = true;
1972         }
1973         else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
1974            decoder->private_->header_warmup[1] = (FLAC__byte)x;
1975            decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
1976            return true;
1977         }
1978      }
1979      if(first) {
1980         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
1981         first = false;
1982      }
1983   }
1984
1985   return true;
1986}
1987
1988FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
1989{
1990   unsigned channel;
1991   unsigned i;
1992   FLAC__int32 mid, side;
1993   unsigned frame_crc; /* the one we calculate from the input stream */
1994   FLAC__uint32 x;
1995
1996   *got_a_frame = false;
1997
1998   /* init the CRC */
1999   frame_crc = 0;
2000   frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
2001   frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
2002   FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
2003
2004   if(!read_frame_header_(decoder))
2005      return false;
2006   if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
2007      return true;
2008   if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
2009      return false;
2010   for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2011      /*
2012       * first figure the correct bits-per-sample of the subframe
2013       */
2014      unsigned bps = decoder->private_->frame.header.bits_per_sample;
2015      switch(decoder->private_->frame.header.channel_assignment) {
2016         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2017            /* no adjustment needed */
2018            break;
2019         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2020            FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2021            if(channel == 1)
2022               bps++;
2023            break;
2024         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2025            FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2026            if(channel == 0)
2027               bps++;
2028            break;
2029         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2030            FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2031            if(channel == 1)
2032               bps++;
2033            break;
2034         default:
2035            FLAC__ASSERT(0);
2036      }
2037      /*
2038       * now read it
2039       */
2040      if(!read_subframe_(decoder, channel, bps, do_full_decode))
2041         return false;
2042      if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2043         return true;
2044   }
2045   if(!read_zero_padding_(decoder))
2046      return false;
2047   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) */
2048      return true;
2049
2050   /*
2051    * Read the frame CRC-16 from the footer and check
2052    */
2053   frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
2054   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
2055      return false; /* read_callback_ sets the state for us */
2056   if(frame_crc == x) {
2057      if(do_full_decode) {
2058         /* Undo any special channel coding */
2059         switch(decoder->private_->frame.header.channel_assignment) {
2060            case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
2061               /* do nothing */
2062               break;
2063            case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
2064               FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2065               for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2066                  decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
2067               break;
2068            case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2069               FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2070               for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2071                  decoder->private_->output[0][i] += decoder->private_->output[1][i];
2072               break;
2073            case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
2074               FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
2075               for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2076#if 1
2077                  mid = decoder->private_->output[0][i];
2078                  side = decoder->private_->output[1][i];
2079                  mid <<= 1;
2080                  mid |= (side & 1); /* i.e. if 'side' is odd... */
2081                  decoder->private_->output[0][i] = (mid + side) >> 1;
2082                  decoder->private_->output[1][i] = (mid - side) >> 1;
2083#else
2084                  /* OPT: without 'side' temp variable */
2085                  mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
2086                  decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
2087                  decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
2088#endif
2089               }
2090               break;
2091            default:
2092               FLAC__ASSERT(0);
2093               break;
2094         }
2095      }
2096   }
2097   else {
2098      /* Bad frame, emit error and zero the output signal */
2099      send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
2100      if(do_full_decode) {
2101         for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
2102            memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2103         }
2104      }
2105   }
2106
2107   *got_a_frame = true;
2108
2109   /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
2110   if(decoder->private_->next_fixed_block_size)
2111      decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
2112
2113   /* put the latest values into the public section of the decoder instance */
2114   decoder->protected_->channels = decoder->private_->frame.header.channels;
2115   decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
2116   decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
2117   decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
2118   decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
2119
2120   FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2121   decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
2122
2123   /* write it */
2124   if(do_full_decode) {
2125      if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
2126         return false;
2127   }
2128
2129   decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2130   return true;
2131}
2132
2133FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
2134{
2135   FLAC__uint32 x;
2136   FLAC__uint64 xx;
2137   unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
2138   FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
2139   unsigned raw_header_len;
2140   FLAC__bool is_unparseable = false;
2141
2142   FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
2143
2144   /* init the raw header with the saved bits from synchronization */
2145   raw_header[0] = decoder->private_->header_warmup[0];
2146   raw_header[1] = decoder->private_->header_warmup[1];
2147   raw_header_len = 2;
2148
2149   /* check to make sure that reserved bit is 0 */
2150   if(raw_header[1] & 0x02) /* MAGIC NUMBER */
2151      is_unparseable = true;
2152
2153   /*
2154    * Note that along the way as we read the header, we look for a sync
2155    * code inside.  If we find one it would indicate that our original
2156    * sync was bad since there cannot be a sync code in a valid header.
2157    *
2158    * Three kinds of things can go wrong when reading the frame header:
2159    *  1) We may have sync'ed incorrectly and not landed on a frame header.
2160    *     If we don't find a sync code, it can end up looking like we read
2161    *     a valid but unparseable header, until getting to the frame header
2162    *     CRC.  Even then we could get a false positive on the CRC.
2163    *  2) We may have sync'ed correctly but on an unparseable frame (from a
2164    *     future encoder).
2165    *  3) We may be on a damaged frame which appears valid but unparseable.
2166    *
2167    * For all these reasons, we try and read a complete frame header as
2168    * long as it seems valid, even if unparseable, up until the frame
2169    * header CRC.
2170    */
2171
2172   /*
2173    * read in the raw header as bytes so we can CRC it, and parse it on the way
2174    */
2175   for(i = 0; i < 2; i++) {
2176      if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2177         return false; /* read_callback_ sets the state for us */
2178      if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
2179         /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
2180         decoder->private_->lookahead = (FLAC__byte)x;
2181         decoder->private_->cached = true;
2182         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2183         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2184         return true;
2185      }
2186      raw_header[raw_header_len++] = (FLAC__byte)x;
2187   }
2188
2189   switch(x = raw_header[2] >> 4) {
2190      case 0:
2191         is_unparseable = true;
2192         break;
2193      case 1:
2194         decoder->private_->frame.header.blocksize = 192;
2195         break;
2196      case 2:
2197      case 3:
2198      case 4:
2199      case 5:
2200         decoder->private_->frame.header.blocksize = 576 << (x-2);
2201         break;
2202      case 6:
2203      case 7:
2204         blocksize_hint = x;
2205         break;
2206      case 8:
2207      case 9:
2208      case 10:
2209      case 11:
2210      case 12:
2211      case 13:
2212      case 14:
2213      case 15:
2214         decoder->private_->frame.header.blocksize = 256 << (x-8);
2215         break;
2216      default:
2217         FLAC__ASSERT(0);
2218         break;
2219   }
2220
2221   switch(x = raw_header[2] & 0x0f) {
2222      case 0:
2223         if(decoder->private_->has_stream_info)
2224            decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
2225         else
2226            is_unparseable = true;
2227         break;
2228      case 1:
2229         decoder->private_->frame.header.sample_rate = 88200;
2230         break;
2231      case 2:
2232         decoder->private_->frame.header.sample_rate = 176400;
2233         break;
2234      case 3:
2235         decoder->private_->frame.header.sample_rate = 192000;
2236         break;
2237      case 4:
2238         decoder->private_->frame.header.sample_rate = 8000;
2239         break;
2240      case 5:
2241         decoder->private_->frame.header.sample_rate = 16000;
2242         break;
2243      case 6:
2244         decoder->private_->frame.header.sample_rate = 22050;
2245         break;
2246      case 7:
2247         decoder->private_->frame.header.sample_rate = 24000;
2248         break;
2249      case 8:
2250         decoder->private_->frame.header.sample_rate = 32000;
2251         break;
2252      case 9:
2253         decoder->private_->frame.header.sample_rate = 44100;
2254         break;
2255      case 10:
2256         decoder->private_->frame.header.sample_rate = 48000;
2257         break;
2258      case 11:
2259         decoder->private_->frame.header.sample_rate = 96000;
2260         break;
2261      case 12:
2262      case 13:
2263      case 14:
2264         sample_rate_hint = x;
2265         break;
2266      case 15:
2267         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2268         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2269         return true;
2270      default:
2271         FLAC__ASSERT(0);
2272   }
2273
2274   x = (unsigned)(raw_header[3] >> 4);
2275   if(x & 8) {
2276      decoder->private_->frame.header.channels = 2;
2277      switch(x & 7) {
2278         case 0:
2279            decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
2280            break;
2281         case 1:
2282            decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
2283            break;
2284         case 2:
2285            decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
2286            break;
2287         default:
2288            is_unparseable = true;
2289            break;
2290      }
2291   }
2292   else {
2293      decoder->private_->frame.header.channels = (unsigned)x + 1;
2294      decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
2295   }
2296
2297   switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
2298      case 0:
2299         if(decoder->private_->has_stream_info)
2300            decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2301         else
2302            is_unparseable = true;
2303         break;
2304      case 1:
2305         decoder->private_->frame.header.bits_per_sample = 8;
2306         break;
2307      case 2:
2308         decoder->private_->frame.header.bits_per_sample = 12;
2309         break;
2310      case 4:
2311         decoder->private_->frame.header.bits_per_sample = 16;
2312         break;
2313      case 5:
2314         decoder->private_->frame.header.bits_per_sample = 20;
2315         break;
2316      case 6:
2317         decoder->private_->frame.header.bits_per_sample = 24;
2318         break;
2319      case 3:
2320      case 7:
2321         is_unparseable = true;
2322         break;
2323      default:
2324         FLAC__ASSERT(0);
2325         break;
2326   }
2327
2328   /* check to make sure that reserved bit is 0 */
2329   if(raw_header[3] & 0x01) /* MAGIC NUMBER */
2330      is_unparseable = true;
2331
2332   /* read the frame's starting sample number (or frame number as the case may be) */
2333   if(
2334      raw_header[1] & 0x01 ||
2335      /*@@@ 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 */
2336      (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
2337   ) { /* variable blocksize */
2338      if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
2339         return false; /* read_callback_ sets the state for us */
2340      if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
2341         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2342         decoder->private_->cached = true;
2343         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2344         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2345         return true;
2346      }
2347      decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2348      decoder->private_->frame.header.number.sample_number = xx;
2349   }
2350   else { /* fixed blocksize */
2351      if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
2352         return false; /* read_callback_ sets the state for us */
2353      if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
2354         decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
2355         decoder->private_->cached = true;
2356         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2357         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2358         return true;
2359      }
2360      decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2361      decoder->private_->frame.header.number.frame_number = x;
2362   }
2363
2364   if(blocksize_hint) {
2365      if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2366         return false; /* read_callback_ sets the state for us */
2367      raw_header[raw_header_len++] = (FLAC__byte)x;
2368      if(blocksize_hint == 7) {
2369         FLAC__uint32 _x;
2370         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2371            return false; /* read_callback_ sets the state for us */
2372         raw_header[raw_header_len++] = (FLAC__byte)_x;
2373         x = (x << 8) | _x;
2374      }
2375      decoder->private_->frame.header.blocksize = x+1;
2376   }
2377
2378   if(sample_rate_hint) {
2379      if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2380         return false; /* read_callback_ sets the state for us */
2381      raw_header[raw_header_len++] = (FLAC__byte)x;
2382      if(sample_rate_hint != 12) {
2383         FLAC__uint32 _x;
2384         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
2385            return false; /* read_callback_ sets the state for us */
2386         raw_header[raw_header_len++] = (FLAC__byte)_x;
2387         x = (x << 8) | _x;
2388      }
2389      if(sample_rate_hint == 12)
2390         decoder->private_->frame.header.sample_rate = x*1000;
2391      else if(sample_rate_hint == 13)
2392         decoder->private_->frame.header.sample_rate = x;
2393      else
2394         decoder->private_->frame.header.sample_rate = x*10;
2395   }
2396
2397   /* read the CRC-8 byte */
2398   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
2399      return false; /* read_callback_ sets the state for us */
2400   crc8 = (FLAC__byte)x;
2401
2402   if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
2403      send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
2404      decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2405      return true;
2406   }
2407
2408   /* calculate the sample number from the frame number if needed */
2409   decoder->private_->next_fixed_block_size = 0;
2410   if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
2411      x = decoder->private_->frame.header.number.frame_number;
2412      decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
2413      if(decoder->private_->fixed_block_size)
2414         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
2415      else if(decoder->private_->has_stream_info) {
2416         if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
2417            decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
2418            decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
2419         }
2420         else
2421            is_unparseable = true;
2422      }
2423      else if(x == 0) {
2424         decoder->private_->frame.header.number.sample_number = 0;
2425         decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
2426      }
2427      else {
2428         /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
2429         decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
2430      }
2431   }
2432
2433   if(is_unparseable) {
2434      send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2435      decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2436      return true;
2437   }
2438
2439   return true;
2440}
2441
2442FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2443{
2444   FLAC__uint32 x;
2445   FLAC__bool wasted_bits;
2446   unsigned i;
2447
2448   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
2449      return false; /* read_callback_ sets the state for us */
2450
2451   wasted_bits = (x & 1);
2452   x &= 0xfe;
2453
2454   if(wasted_bits) {
2455      unsigned u;
2456      if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
2457         return false; /* read_callback_ sets the state for us */
2458      decoder->private_->frame.subframes[channel].wasted_bits = u+1;
2459      bps -= decoder->private_->frame.subframes[channel].wasted_bits;
2460   }
2461   else
2462      decoder->private_->frame.subframes[channel].wasted_bits = 0;
2463
2464   /*
2465    * Lots of magic numbers here
2466    */
2467   if(x & 0x80) {
2468      send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2469      decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2470      return true;
2471   }
2472   else if(x == 0) {
2473      if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
2474         return false;
2475   }
2476   else if(x == 2) {
2477      if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
2478         return false;
2479   }
2480   else if(x < 16) {
2481      send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2482      decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2483      return true;
2484   }
2485   else if(x <= 24) {
2486      if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
2487         return false;
2488      if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2489         return true;
2490   }
2491   else if(x < 64) {
2492      send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2493      decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2494      return true;
2495   }
2496   else {
2497      if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
2498         return false;
2499      if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
2500         return true;
2501   }
2502
2503   if(wasted_bits && do_full_decode) {
2504      x = decoder->private_->frame.subframes[channel].wasted_bits;
2505      for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2506         decoder->private_->output[channel][i] <<= x;
2507   }
2508
2509   return true;
2510}
2511
2512FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2513{
2514   FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
2515   FLAC__int32 x;
2516   unsigned i;
2517   FLAC__int32 *output = decoder->private_->output[channel];
2518
2519   decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
2520
2521   if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2522      return false; /* read_callback_ sets the state for us */
2523
2524   subframe->value = x;
2525
2526   /* decode the subframe */
2527   if(do_full_decode) {
2528      for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
2529         output[i] = x;
2530   }
2531
2532   return true;
2533}
2534
2535FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2536{
2537   FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
2538   FLAC__int32 i32;
2539   FLAC__uint32 u32;
2540   unsigned u;
2541
2542   decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
2543
2544   subframe->residual = decoder->private_->residual[channel];
2545   subframe->order = order;
2546
2547   /* read warm-up samples */
2548   for(u = 0; u < order; u++) {
2549      if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2550         return false; /* read_callback_ sets the state for us */
2551      subframe->warmup[u] = i32;
2552   }
2553
2554   /* read entropy coding method info */
2555   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2556      return false; /* read_callback_ sets the state for us */
2557   subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2558   switch(subframe->entropy_coding_method.type) {
2559      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2560      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2561         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2562            return false; /* read_callback_ sets the state for us */
2563         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2564         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2565         break;
2566      default:
2567         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2568         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2569         return true;
2570   }
2571
2572   /* read residual */
2573   switch(subframe->entropy_coding_method.type) {
2574      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2575      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2576         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))
2577            return false;
2578         break;
2579      default:
2580         FLAC__ASSERT(0);
2581   }
2582
2583   /* decode the subframe */
2584   if(do_full_decode) {
2585      memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2586      FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
2587   }
2588
2589   return true;
2590}
2591
2592FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
2593{
2594   FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
2595   FLAC__int32 i32;
2596   FLAC__uint32 u32;
2597   unsigned u;
2598
2599   decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
2600
2601   subframe->residual = decoder->private_->residual[channel];
2602   subframe->order = order;
2603
2604   /* read warm-up samples */
2605   for(u = 0; u < order; u++) {
2606      if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
2607         return false; /* read_callback_ sets the state for us */
2608      subframe->warmup[u] = i32;
2609   }
2610
2611   /* read qlp coeff precision */
2612   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
2613      return false; /* read_callback_ sets the state for us */
2614   if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
2615      send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2616      decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2617      return true;
2618   }
2619   subframe->qlp_coeff_precision = u32+1;
2620
2621   /* read qlp shift */
2622   if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
2623      return false; /* read_callback_ sets the state for us */
2624   subframe->quantization_level = i32;
2625
2626   /* read quantized lp coefficiencts */
2627   for(u = 0; u < order; u++) {
2628      if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
2629         return false; /* read_callback_ sets the state for us */
2630      subframe->qlp_coeff[u] = i32;
2631   }
2632
2633   /* read entropy coding method info */
2634   if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
2635      return false; /* read_callback_ sets the state for us */
2636   subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
2637   switch(subframe->entropy_coding_method.type) {
2638      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2639      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2640         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
2641            return false; /* read_callback_ sets the state for us */
2642         subframe->entropy_coding_method.data.partitioned_rice.order = u32;
2643         subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
2644         break;
2645      default:
2646         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
2647         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2648         return true;
2649   }
2650
2651   /* read residual */
2652   switch(subframe->entropy_coding_method.type) {
2653      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
2654      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
2655         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))
2656            return false;
2657         break;
2658      default:
2659         FLAC__ASSERT(0);
2660   }
2661
2662   /* decode the subframe */
2663   if(do_full_decode) {
2664      memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
2665      /*@@@@@@ technically not pessimistic enough, should be more like
2666      if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
2667      */
2668      if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
2669         if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
2670            if(order <= 8)
2671               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);
2672            else
2673               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);
2674         }
2675         else
2676            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);
2677      else
2678         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);
2679   }
2680
2681   return true;
2682}
2683
2684FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
2685{
2686   FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
2687   FLAC__int32 x, *residual = decoder->private_->residual[channel];
2688   unsigned i;
2689
2690   decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
2691
2692   subframe->data = residual;
2693
2694   for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
2695      if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
2696         return false; /* read_callback_ sets the state for us */
2697      residual[i] = x;
2698   }
2699
2700   /* decode the subframe */
2701   if(do_full_decode)
2702      memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
2703
2704   return true;
2705}
2706
2707FLAC__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)
2708{
2709   FLAC__uint32 rice_parameter;
2710   int i;
2711   unsigned partition, sample, u;
2712   const unsigned partitions = 1u << partition_order;
2713   const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
2714   const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
2715   const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
2716
2717   /* sanity checks */
2718   if(partition_order == 0) {
2719      if(decoder->private_->frame.header.blocksize < predictor_order) {
2720         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2721         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2722         return true;
2723      }
2724   }
2725   else {
2726      if(partition_samples < predictor_order) {
2727         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2728         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2729         return true;
2730      }
2731   }
2732
2733   if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
2734      decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
2735      return false;
2736   }
2737
2738   sample = 0;
2739   for(partition = 0; partition < partitions; partition++) {
2740      if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
2741         return false; /* read_callback_ sets the state for us */
2742      partitioned_rice_contents->parameters[partition] = rice_parameter;
2743      if(rice_parameter < pesc) {
2744         partitioned_rice_contents->raw_bits[partition] = 0;
2745         u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
2746         if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, residual + sample, u, rice_parameter))
2747            return false; /* read_callback_ sets the state for us */
2748         sample += u;
2749      }
2750      else {
2751         if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
2752            return false; /* read_callback_ sets the state for us */
2753         partitioned_rice_contents->raw_bits[partition] = rice_parameter;
2754         for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
2755            if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i, rice_parameter))
2756               return false; /* read_callback_ sets the state for us */
2757            residual[sample] = i;
2758         }
2759      }
2760   }
2761
2762   return true;
2763}
2764
2765FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
2766{
2767   if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
2768      FLAC__uint32 zero = 0;
2769      if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
2770         return false; /* read_callback_ sets the state for us */
2771      if(zero != 0) {
2772         send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
2773         decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
2774      }
2775   }
2776   return true;
2777}
2778
2779FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
2780{
2781   FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
2782
2783   if(
2784#if FLAC__HAS_OGG
2785      /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2786      !decoder->private_->is_ogg &&
2787#endif
2788      decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2789   ) {
2790      *bytes = 0;
2791      decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2792      return false;
2793   }
2794   else if(*bytes > 0) {
2795      /* While seeking, it is possible for our seek to land in the
2796       * middle of audio data that looks exactly like a frame header
2797       * from a future version of an encoder.  When that happens, our
2798       * error callback will get an
2799       * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
2800       * unparseable_frame_count.  But there is a remote possibility
2801       * that it is properly synced at such a "future-codec frame",
2802       * so to make sure, we wait to see many "unparseable" errors in
2803       * a row before bailing out.
2804       */
2805      if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
2806         decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2807         return false;
2808      }
2809      else {
2810         const FLAC__StreamDecoderReadStatus status =
2811#if FLAC__HAS_OGG
2812            decoder->private_->is_ogg?
2813            read_callback_ogg_aspect_(decoder, buffer, bytes) :
2814#endif
2815            decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
2816         ;
2817         if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
2818            decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2819            return false;
2820         }
2821         else if(*bytes == 0) {
2822            if(
2823               status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
2824               (
2825#if FLAC__HAS_OGG
2826                  /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
2827                  !decoder->private_->is_ogg &&
2828#endif
2829                  decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
2830               )
2831            ) {
2832               decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
2833               return false;
2834            }
2835            else
2836               return true;
2837         }
2838         else
2839            return true;
2840      }
2841   }
2842   else {
2843      /* abort to avoid a deadlock */
2844      decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
2845      return false;
2846   }
2847   /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
2848    * for Ogg FLAC.  This is because the ogg decoder aspect can lose sync
2849    * and at the same time hit the end of the stream (for example, seeking
2850    * to a point that is after the beginning of the last Ogg page).  There
2851    * is no way to report an Ogg sync loss through the callbacks (see note
2852    * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
2853    * So to keep the decoder from stopping at this point we gate the call
2854    * to the eof_callback and let the Ogg decoder aspect set the
2855    * end-of-stream state when it is needed.
2856    */
2857}
2858
2859#if FLAC__HAS_OGG
2860FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
2861{
2862   switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
2863      case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
2864         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2865      /* we don't really have a way to handle lost sync via read
2866       * callback so we'll let it pass and let the underlying
2867       * FLAC decoder catch the error
2868       */
2869      case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
2870         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
2871      case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
2872         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
2873      case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
2874      case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
2875      case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
2876      case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
2877      case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
2878         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2879      default:
2880         FLAC__ASSERT(0);
2881         /* double protection */
2882         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
2883   }
2884}
2885
2886FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
2887{
2888   FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
2889
2890   switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
2891      case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
2892         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
2893      case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
2894         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
2895      case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
2896         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2897      default:
2898         /* double protection: */
2899         FLAC__ASSERT(0);
2900         return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
2901   }
2902}
2903#endif
2904
2905FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
2906{
2907   if(decoder->private_->is_seeking) {
2908      FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
2909      FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
2910      FLAC__uint64 target_sample = decoder->private_->target_sample;
2911
2912      FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
2913
2914#if FLAC__HAS_OGG
2915      decoder->private_->got_a_frame = true;
2916#endif
2917      decoder->private_->last_frame = *frame; /* save the frame */
2918      if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
2919         unsigned delta = (unsigned)(target_sample - this_frame_sample);
2920         /* kick out of seek mode */
2921         decoder->private_->is_seeking = false;
2922         /* shift out the samples before target_sample */
2923         if(delta > 0) {
2924            unsigned channel;
2925            const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
2926            for(channel = 0; channel < frame->header.channels; channel++)
2927               newbuffer[channel] = buffer[channel] + delta;
2928            decoder->private_->last_frame.header.blocksize -= delta;
2929            decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
2930            /* write the relevant samples */
2931            return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
2932         }
2933         else {
2934            /* write the relevant samples */
2935            return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2936         }
2937      }
2938      else {
2939         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
2940      }
2941   }
2942   else {
2943      /*
2944       * If we never got STREAMINFO, turn off MD5 checking to save
2945       * cycles since we don't have a sum to compare to anyway
2946       */
2947      if(!decoder->private_->has_stream_info)
2948         decoder->private_->do_md5_checking = false;
2949      if(decoder->private_->do_md5_checking) {
2950         if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
2951            return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
2952      }
2953      return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
2954   }
2955}
2956
2957void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
2958{
2959   if(!decoder->private_->is_seeking)
2960      decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
2961   else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
2962      decoder->private_->unparseable_frame_count++;
2963}
2964
2965FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
2966{
2967   FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
2968   FLAC__int64 pos = -1;
2969   int i;
2970   unsigned approx_bytes_per_frame;
2971   FLAC__bool first_seek = true;
2972   const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
2973   const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
2974   const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
2975   const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
2976   const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
2977   /* take these from the current frame in case they've changed mid-stream */
2978   unsigned channels = FLAC__stream_decoder_get_channels(decoder);
2979   unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
2980   const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
2981
2982   /* use values from stream info if we didn't decode a frame */
2983   if(channels == 0)
2984      channels = decoder->private_->stream_info.data.stream_info.channels;
2985   if(bps == 0)
2986      bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
2987
2988   /* we are just guessing here */
2989   if(max_framesize > 0)
2990      approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
2991   /*
2992    * Check if it's a known fixed-blocksize stream.  Note that though
2993    * the spec doesn't allow zeroes in the STREAMINFO block, we may
2994    * never get a STREAMINFO block when decoding so the value of
2995    * min_blocksize might be zero.
2996    */
2997   else if(min_blocksize == max_blocksize && min_blocksize > 0) {
2998      /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
2999      approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
3000   }
3001   else
3002      approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
3003
3004   /*
3005    * First, we set an upper and lower bound on where in the
3006    * stream we will search.  For now we assume the worst case
3007    * scenario, which is our best guess at the beginning of
3008    * the first frame and end of the stream.
3009    */
3010   lower_bound = first_frame_offset;
3011   lower_bound_sample = 0;
3012   upper_bound = stream_length;
3013   upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
3014
3015   /*
3016    * Now we refine the bounds if we have a seektable with
3017    * suitable points.  Note that according to the spec they
3018    * must be ordered by ascending sample number.
3019    *
3020    * Note: to protect against invalid seek tables we will ignore points
3021    * that have frame_samples==0 or sample_number>=total_samples
3022    */
3023   if(seek_table) {
3024      FLAC__uint64 new_lower_bound = lower_bound;
3025      FLAC__uint64 new_upper_bound = upper_bound;
3026      FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
3027      FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
3028
3029      /* find the closest seek point <= target_sample, if it exists */
3030      for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
3031         if(
3032            seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
3033            seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
3034            (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
3035            seek_table->points[i].sample_number <= target_sample
3036         )
3037            break;
3038      }
3039      if(i >= 0) { /* i.e. we found a suitable seek point... */
3040         new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
3041         new_lower_bound_sample = seek_table->points[i].sample_number;
3042      }
3043
3044      /* find the closest seek point > target_sample, if it exists */
3045      for(i = 0; i < (int)seek_table->num_points; i++) {
3046         if(
3047            seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
3048            seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
3049            (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
3050            seek_table->points[i].sample_number > target_sample
3051         )
3052            break;
3053      }
3054      if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
3055         new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
3056         new_upper_bound_sample = seek_table->points[i].sample_number;
3057      }
3058      /* final protection against unsorted seek tables; keep original values if bogus */
3059      if(new_upper_bound >= new_lower_bound) {
3060         lower_bound = new_lower_bound;
3061         upper_bound = new_upper_bound;
3062         lower_bound_sample = new_lower_bound_sample;
3063         upper_bound_sample = new_upper_bound_sample;
3064      }
3065   }
3066
3067   FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
3068   /* there are 2 insidious ways that the following equality occurs, which
3069    * we need to fix:
3070    *  1) total_samples is 0 (unknown) and target_sample is 0
3071    *  2) total_samples is 0 (unknown) and target_sample happens to be
3072    *     exactly equal to the last seek point in the seek table; this
3073    *     means there is no seek point above it, and upper_bound_samples
3074    *     remains equal to the estimate (of target_samples) we made above
3075    * in either case it does not hurt to move upper_bound_sample up by 1
3076    */
3077   if(upper_bound_sample == lower_bound_sample)
3078      upper_bound_sample++;
3079
3080   decoder->private_->target_sample = target_sample;
3081   while(1) {
3082      /* check if the bounds are still ok */
3083      if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
3084         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3085         return false;
3086      }
3087#ifndef FLAC__INTEGER_ONLY_LIBRARY
3088#if defined _MSC_VER || defined __MINGW32__
3089      /* with VC++ you have to spoon feed it the casting */
3090      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;
3091#else
3092      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;
3093#endif
3094#else
3095      /* a little less accurate: */
3096      if(upper_bound - lower_bound < 0xffffffff)
3097         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;
3098      else /* @@@ WATCHOUT, ~2TB limit */
3099         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;
3100#endif
3101      if(pos >= (FLAC__int64)upper_bound)
3102         pos = (FLAC__int64)upper_bound - 1;
3103      if(pos < (FLAC__int64)lower_bound)
3104         pos = (FLAC__int64)lower_bound;
3105      if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3106         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3107         return false;
3108      }
3109      if(!FLAC__stream_decoder_flush(decoder)) {
3110         /* above call sets the state for us */
3111         return false;
3112      }
3113      /* Now we need to get a frame.  First we need to reset our
3114       * unparseable_frame_count; if we get too many unparseable
3115       * frames in a row, the read callback will return
3116       * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
3117       * FLAC__stream_decoder_process_single() to return false.
3118       */
3119      decoder->private_->unparseable_frame_count = 0;
3120      if(!FLAC__stream_decoder_process_single(decoder)) {
3121         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3122         return false;
3123      }
3124      /* our write callback will change the state when it gets to the target frame */
3125      /* 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 */
3126#if 0
3127      /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
3128      if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
3129         break;
3130#endif
3131      if(!decoder->private_->is_seeking)
3132         break;
3133
3134      FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3135      this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3136
3137      if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
3138         if (pos == (FLAC__int64)lower_bound) {
3139            /* can't move back any more than the first frame, something is fatally wrong */
3140            decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3141            return false;
3142         }
3143         /* our last move backwards wasn't big enough, try again */
3144         approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
3145         continue;   
3146      }
3147      /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
3148      first_seek = false;
3149     
3150      /* make sure we are not seeking in corrupted stream */
3151      if (this_frame_sample < lower_bound_sample) {
3152         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3153         return false;
3154      }
3155
3156      /* we need to narrow the search */
3157      if(target_sample < this_frame_sample) {
3158         upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3159/*@@@@@@ what will decode position be if at end of stream? */
3160         if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
3161            decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3162            return false;
3163         }
3164         approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
3165      }
3166      else { /* target_sample >= this_frame_sample + this frame's blocksize */
3167         lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
3168         if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
3169            decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3170            return false;
3171         }
3172         approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
3173      }
3174   }
3175
3176   return true;
3177}
3178
3179#if FLAC__HAS_OGG
3180FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
3181{
3182   FLAC__uint64 left_pos = 0, right_pos = stream_length;
3183   FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
3184   FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
3185   FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
3186   FLAC__bool did_a_seek;
3187   unsigned iteration = 0;
3188
3189   /* In the first iterations, we will calculate the target byte position
3190    * by the distance from the target sample to left_sample and
3191    * right_sample (let's call it "proportional search").  After that, we
3192    * will switch to binary search.
3193    */
3194   unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
3195
3196   /* We will switch to a linear search once our current sample is less
3197    * than this number of samples ahead of the target sample
3198    */
3199   static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
3200
3201   /* If the total number of samples is unknown, use a large value, and
3202    * force binary search immediately.
3203    */
3204   if(right_sample == 0) {
3205      right_sample = (FLAC__uint64)(-1);
3206      BINARY_SEARCH_AFTER_ITERATION = 0;
3207   }
3208
3209   decoder->private_->target_sample = target_sample;
3210   for( ; ; iteration++) {
3211      if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
3212         if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
3213            pos = (right_pos + left_pos) / 2;
3214         }
3215         else {
3216#ifndef FLAC__INTEGER_ONLY_LIBRARY
3217#if defined _MSC_VER || defined __MINGW32__
3218            /* with MSVC you have to spoon feed it the casting */
3219            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));
3220#else
3221            pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
3222#endif
3223#else
3224            /* a little less accurate: */
3225            if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
3226               pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
3227            else /* @@@ WATCHOUT, ~2TB limit */
3228               pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
3229#endif
3230            /* @@@ TODO: might want to limit pos to some distance
3231             * before EOF, to make sure we land before the last frame,
3232             * thereby getting a this_frame_sample and so having a better
3233             * estimate.
3234             */
3235         }
3236
3237         /* physical seek */
3238         if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
3239            decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3240            return false;
3241         }
3242         if(!FLAC__stream_decoder_flush(decoder)) {
3243            /* above call sets the state for us */
3244            return false;
3245         }
3246         did_a_seek = true;
3247      }
3248      else
3249         did_a_seek = false;
3250
3251      decoder->private_->got_a_frame = false;
3252      if(!FLAC__stream_decoder_process_single(decoder)) {
3253         decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3254         return false;
3255      }
3256      if(!decoder->private_->got_a_frame) {
3257         if(did_a_seek) {
3258            /* this can happen if we seek to a point after the last frame; we drop
3259             * to binary search right away in this case to avoid any wasted
3260             * iterations of proportional search.
3261             */
3262            right_pos = pos;
3263            BINARY_SEARCH_AFTER_ITERATION = 0;
3264         }
3265         else {
3266            /* this can probably only happen if total_samples is unknown and the
3267             * target_sample is past the end of the stream
3268             */
3269            decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3270            return false;
3271         }
3272      }
3273      /* our write callback will change the state when it gets to the target frame */
3274      else if(!decoder->private_->is_seeking) {
3275         break;
3276      }
3277      else {
3278         this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
3279         FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
3280
3281         if (did_a_seek) {
3282            if (this_frame_sample <= target_sample) {
3283               /* The 'equal' case should not happen, since
3284                * FLAC__stream_decoder_process_single()
3285                * should recognize that it has hit the
3286                * target sample and we would exit through
3287                * the 'break' above.
3288                */
3289               FLAC__ASSERT(this_frame_sample != target_sample);
3290
3291               left_sample = this_frame_sample;
3292               /* sanity check to avoid infinite loop */
3293               if (left_pos == pos) {
3294                  decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3295                  return false;
3296               }
3297               left_pos = pos;
3298            }
3299            else if(this_frame_sample > target_sample) {
3300               right_sample = this_frame_sample;
3301               /* sanity check to avoid infinite loop */
3302               if (right_pos == pos) {
3303                  decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
3304                  return false;
3305               }
3306               right_pos = pos;
3307            }
3308         }
3309      }
3310   }
3311
3312   return true;
3313}
3314#endif
3315
3316FLAC__StreamDecoderReadStatus file_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
3317{
3318   (void)client_data;
3319
3320   if(*bytes > 0) {
3321      *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
3322      if(ferror(decoder->private_->file))
3323         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
3324      else if(*bytes == 0)
3325         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
3326      else
3327         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3328   }
3329   else
3330      return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
3331}
3332
3333FLAC__StreamDecoderSeekStatus file_seek_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
3334{
3335   (void)client_data;
3336
3337   if(decoder->private_->file == stdin)
3338      return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
3339   else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
3340      return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
3341   else
3342      return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
3343}
3344
3345FLAC__StreamDecoderTellStatus file_tell_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
3346{
3347   off_t pos;
3348   (void)client_data;
3349
3350   if(decoder->private_->file == stdin)
3351      return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
3352   else if((pos = ftello(decoder->private_->file)) < 0)
3353      return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
3354   else {
3355      *absolute_byte_offset = (FLAC__uint64)pos;
3356      return FLAC__STREAM_DECODER_TELL_STATUS_OK;
3357   }
3358}
3359
3360FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
3361{
3362   struct stat filestats;
3363   (void)client_data;
3364
3365   if(decoder->private_->file == stdin)
3366      return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
3367   else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
3368      return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
3369   else {
3370      *stream_length = (FLAC__uint64)filestats.st_size;
3371      return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
3372   }
3373}
3374
3375FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
3376{
3377   (void)client_data;
3378
3379   return feof(decoder->private_->file)? true : false;
3380}
src/lib/libflac/libflac/md5.c
r0r14135
1#if HAVE_CONFIG_H
2#  include <config.h>
3#endif
4
5#include <stdlib.h>      /* for malloc() */
6#include <string.h>      /* for memcpy() */
7
8#include "private/md5.h"
9#include "share/alloc.h"
10
11#ifndef FLaC__INLINE
12#define FLaC__INLINE
13#endif
14
15/*
16 * This code implements the MD5 message-digest algorithm.
17 * The algorithm is due to Ron Rivest.  This code was
18 * written by Colin Plumb in 1993, no copyright is claimed.
19 * This code is in the public domain; do with it what you wish.
20 *
21 * Equivalent code is available from RSA Data Security, Inc.
22 * This code has been tested against that, and is equivalent,
23 * except that you don't need to include two pages of legalese
24 * with every copy.
25 *
26 * To compute the message digest of a chunk of bytes, declare an
27 * MD5Context structure, pass it to MD5Init, call MD5Update as
28 * needed on buffers full of bytes, and then call MD5Final, which
29 * will fill a supplied 16-byte array with the digest.
30 *
31 * Changed so as no longer to depend on Colin Plumb's `usual.h' header
32 * definitions; now uses stuff from dpkg's config.h.
33 *  - Ian Jackson <ijackson@nyx.cs.du.edu>.
34 * Still in the public domain.
35 *
36 * Josh Coalson: made some changes to integrate with libFLAC.
37 * Still in the public domain.
38 */
39
40/* The four core functions - F1 is optimized somewhat */
41
42/* #define F1(x, y, z) (x & y | ~x & z) */
43#define F1(x, y, z) (z ^ (x & (y ^ z)))
44#define F2(x, y, z) F1(z, x, y)
45#define F3(x, y, z) (x ^ y ^ z)
46#define F4(x, y, z) (y ^ (x | ~z))
47
48/* This is the central step in the MD5 algorithm. */
49#define MD5STEP(f,w,x,y,z,in,s) \
50    (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
51
52/*
53 * The core of the MD5 algorithm, this alters an existing MD5 hash to
54 * reflect the addition of 16 longwords of new data.  MD5Update blocks
55 * the data and converts bytes into longwords for this routine.
56 */
57static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
58{
59   register FLAC__uint32 a, b, c, d;
60
61   a = buf[0];
62   b = buf[1];
63   c = buf[2];
64   d = buf[3];
65
66   MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
67   MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
68   MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
69   MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
70   MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
71   MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
72   MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
73   MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
74   MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
75   MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
76   MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
77   MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
78   MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
79   MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
80   MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
81   MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
82
83   MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
84   MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
85   MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
86   MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
87   MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
88   MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
89   MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
90   MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
91   MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
92   MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
93   MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
94   MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
95   MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
96   MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
97   MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
98   MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
99
100   MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
101   MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
102   MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
103   MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
104   MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
105   MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
106   MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
107   MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
108   MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
109   MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
110   MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
111   MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
112   MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
113   MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
114   MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
115   MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
116
117   MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
118   MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
119   MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
120   MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
121   MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
122   MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
123   MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
124   MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
125   MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
126   MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
127   MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
128   MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
129   MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
130   MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
131   MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
132   MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
133
134   buf[0] += a;
135   buf[1] += b;
136   buf[2] += c;
137   buf[3] += d;
138}
139
140#if WORDS_BIGENDIAN
141//@@@@@@ OPT: use bswap/intrinsics
142static void byteSwap(FLAC__uint32 *buf, unsigned words)
143{
144   register FLAC__uint32 x;
145   do {
146      x = *buf;
147      x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
148      *buf++ = (x >> 16) | (x << 16);
149   } while (--words);
150}
151static void byteSwapX16(FLAC__uint32 *buf)
152{
153   register FLAC__uint32 x;
154
155   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
156   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
157   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
158   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
159   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
160   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
161   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
162   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
163   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
164   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
165   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
166   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
167   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
168   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
169   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
170   x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf   = (x >> 16) | (x << 16);
171}
172#else
173#define byteSwap(buf, words)
174#define byteSwapX16(buf)
175#endif
176
177/*
178 * Update context to reflect the concatenation of another buffer full
179 * of bytes.
180 */
181static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
182{
183   FLAC__uint32 t;
184
185   /* Update byte count */
186
187   t = ctx->bytes[0];
188   if ((ctx->bytes[0] = t + len) < t)
189      ctx->bytes[1]++;   /* Carry from low to high */
190
191   t = 64 - (t & 0x3f);   /* Space available in ctx->in (at least 1) */
192   if (t > len) {
193      memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
194      return;
195   }
196   /* First chunk is an odd size */
197   memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
198   byteSwapX16(ctx->in);
199   FLAC__MD5Transform(ctx->buf, ctx->in);
200   buf += t;
201   len -= t;
202
203   /* Process data in 64-byte chunks */
204   while (len >= 64) {
205      memcpy(ctx->in, buf, 64);
206      byteSwapX16(ctx->in);
207      FLAC__MD5Transform(ctx->buf, ctx->in);
208      buf += 64;
209      len -= 64;
210   }
211
212   /* Handle any remaining bytes of data. */
213   memcpy(ctx->in, buf, len);
214}
215
216/*
217 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
218 * initialization constants.
219 */
220void FLAC__MD5Init(FLAC__MD5Context *ctx)
221{
222   ctx->buf[0] = 0x67452301;
223   ctx->buf[1] = 0xefcdab89;
224   ctx->buf[2] = 0x98badcfe;
225   ctx->buf[3] = 0x10325476;
226
227   ctx->bytes[0] = 0;
228   ctx->bytes[1] = 0;
229
230   ctx->internal_buf = 0;
231   ctx->capacity = 0;
232}
233
234/*
235 * Final wrapup - pad to 64-byte boundary with the bit pattern
236 * 1 0* (64-bit count of bits processed, MSB-first)
237 */
238void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
239{
240   int count = ctx->bytes[0] & 0x3f;   /* Number of bytes in ctx->in */
241   FLAC__byte *p = (FLAC__byte *)ctx->in + count;
242
243   /* Set the first char of padding to 0x80.  There is always room. */
244   *p++ = 0x80;
245
246   /* Bytes of padding needed to make 56 bytes (-8..55) */
247   count = 56 - 1 - count;
248
249   if (count < 0) {   /* Padding forces an extra block */
250      memset(p, 0, count + 8);
251      byteSwapX16(ctx->in);
252      FLAC__MD5Transform(ctx->buf, ctx->in);
253      p = (FLAC__byte *)ctx->in;
254      count = 56;
255   }
256   memset(p, 0, count);
257   byteSwap(ctx->in, 14);
258
259   /* Append length in bits and transform */
260   ctx->in[14] = ctx->bytes[0] << 3;
261   ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
262   FLAC__MD5Transform(ctx->buf, ctx->in);
263
264   byteSwap(ctx->buf, 4);
265   memcpy(digest, ctx->buf, 16);
266   memset(ctx, 0, sizeof(ctx));   /* In case it's sensitive */
267   if(0 != ctx->internal_buf) {
268      free(ctx->internal_buf);
269      ctx->internal_buf = 0;
270      ctx->capacity = 0;
271   }
272}
273
274/*
275 * Convert the incoming audio signal to a byte stream
276 */
277static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
278{
279   unsigned channel, sample;
280   register FLAC__int32 a_word;
281   register FLAC__byte *buf_ = buf;
282
283#if WORDS_BIGENDIAN
284#else
285   if(channels == 2 && bytes_per_sample == 2) {
286      FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
287      memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
288      for(sample = 0; sample < samples; sample++, buf1_+=2)
289         *buf1_ = (FLAC__int16)signal[1][sample];
290   }
291   else if(channels == 1 && bytes_per_sample == 2) {
292      FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
293      for(sample = 0; sample < samples; sample++)
294         *buf1_++ = (FLAC__int16)signal[0][sample];
295   }
296   else
297#endif
298   if(bytes_per_sample == 2) {
299      if(channels == 2) {
300         for(sample = 0; sample < samples; sample++) {
301            a_word = signal[0][sample];
302            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
303            *buf_++ = (FLAC__byte)a_word;
304            a_word = signal[1][sample];
305            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
306            *buf_++ = (FLAC__byte)a_word;
307         }
308      }
309      else if(channels == 1) {
310         for(sample = 0; sample < samples; sample++) {
311            a_word = signal[0][sample];
312            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
313            *buf_++ = (FLAC__byte)a_word;
314         }
315      }
316      else {
317         for(sample = 0; sample < samples; sample++) {
318            for(channel = 0; channel < channels; channel++) {
319               a_word = signal[channel][sample];
320               *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
321               *buf_++ = (FLAC__byte)a_word;
322            }
323         }
324      }
325   }
326   else if(bytes_per_sample == 3) {
327      if(channels == 2) {
328         for(sample = 0; sample < samples; sample++) {
329            a_word = signal[0][sample];
330            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
331            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
332            *buf_++ = (FLAC__byte)a_word;
333            a_word = signal[1][sample];
334            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
335            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
336            *buf_++ = (FLAC__byte)a_word;
337         }
338      }
339      else if(channels == 1) {
340         for(sample = 0; sample < samples; sample++) {
341            a_word = signal[0][sample];
342            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
343            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
344            *buf_++ = (FLAC__byte)a_word;
345         }
346      }
347      else {
348         for(sample = 0; sample < samples; sample++) {
349            for(channel = 0; channel < channels; channel++) {
350               a_word = signal[channel][sample];
351               *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
352               *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
353               *buf_++ = (FLAC__byte)a_word;
354            }
355         }
356      }
357   }
358   else if(bytes_per_sample == 1) {
359      if(channels == 2) {
360         for(sample = 0; sample < samples; sample++) {
361            a_word = signal[0][sample];
362            *buf_++ = (FLAC__byte)a_word;
363            a_word = signal[1][sample];
364            *buf_++ = (FLAC__byte)a_word;
365         }
366      }
367      else if(channels == 1) {
368         for(sample = 0; sample < samples; sample++) {
369            a_word = signal[0][sample];
370            *buf_++ = (FLAC__byte)a_word;
371         }
372      }
373      else {
374         for(sample = 0; sample < samples; sample++) {
375            for(channel = 0; channel < channels; channel++) {
376               a_word = signal[channel][sample];
377               *buf_++ = (FLAC__byte)a_word;
378            }
379         }
380      }
381   }
382   else { /* bytes_per_sample == 4, maybe optimize more later */
383      for(sample = 0; sample < samples; sample++) {
384         for(channel = 0; channel < channels; channel++) {
385            a_word = signal[channel][sample];
386            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
387            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
388            *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
389            *buf_++ = (FLAC__byte)a_word;
390         }
391      }
392   }
393}
394
395/*
396 * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
397 */
398FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
399{
400   const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
401
402   /* overflow check */
403   if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
404      return false;
405   if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
406      return false;
407
408   if(ctx->capacity < bytes_needed) {
409      FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
410      if(0 == tmp) {
411         free(ctx->internal_buf);
412         if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
413            return false;
414      }
415      ctx->internal_buf = tmp;
416      ctx->capacity = bytes_needed;
417   }
418
419   format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
420
421   FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
422
423   return true;
424}
src/lib/libflac/libflac/cpu.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include "private/cpu.h"
37#include <stdlib.h>
38#include <stdio.h>
39
40#if defined FLAC__CPU_IA32
41# include <signal.h>
42#elif defined FLAC__CPU_PPC
43# if !defined FLAC__NO_ASM
44#  if defined FLAC__SYS_DARWIN
45#   include <sys/sysctl.h>
46#   include <mach/mach.h>
47#   include <mach/mach_host.h>
48#   include <mach/host_info.h>
49#   include <mach/machine.h>
50#   ifndef CPU_SUBTYPE_POWERPC_970
51#    define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
52#   endif
53#  else /* FLAC__SYS_DARWIN */
54
55#   include <signal.h>
56#   include <setjmp.h>
57
58static sigjmp_buf jmpbuf;
59static volatile sig_atomic_t canjump = 0;
60
61static void sigill_handler (int sig)
62{
63   if (!canjump) {
64      signal (sig, SIG_DFL);
65      raise (sig);
66   }
67   canjump = 0;
68   siglongjmp (jmpbuf, 1);
69}
70#  endif /* FLAC__SYS_DARWIN */
71# endif /* FLAC__NO_ASM */
72#endif /* FLAC__CPU_PPC */
73
74#if defined (__NetBSD__) || defined(__OpenBSD__)
75#include <sys/param.h>
76#include <sys/sysctl.h>
77#include <machine/cpu.h>
78#endif
79
80#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
81#include <sys/types.h>
82#include <sys/sysctl.h>
83#endif
84
85#if defined(__APPLE__)
86/* how to get sysctlbyname()? */
87#endif
88
89/* these are flags in EDX of CPUID AX=00000001 */
90static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
91static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
92static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
93static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
94static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
95/* these are flags in ECX of CPUID AX=00000001 */
96static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
97static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
98/* these are flags in EDX of CPUID AX=80000001 */
99static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
100static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
101static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
102
103
104/*
105 * Extra stuff needed for detection of OS support for SSE on IA-32
106 */
107#if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
108# if defined(__linux__)
109/*
110 * If the OS doesn't support SSE, we will get here with a SIGILL.  We
111 * modify the return address to jump over the offending SSE instruction
112 * and also the operation following it that indicates the instruction
113 * executed successfully.  In this way we use no global variables and
114 * stay thread-safe.
115 *
116 * 3 + 3 + 6:
117 *   3 bytes for "xorps xmm0,xmm0"
118 *   3 bytes for estimate of how long the follwing "inc var" instruction is
119 *   6 bytes extra in case our estimate is wrong
120 * 12 bytes puts us in the NOP "landing zone"
121 */
122#  undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
123#  ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
124   static void sigill_handler_sse_os(int signal, struct sigcontext sc)
125   {
126      (void)signal;
127      sc.eip += 3 + 3 + 6;
128   }
129#  else
130#   include <sys/ucontext.h>
131   static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
132   {
133      (void)signal, (void)si;
134      ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
135   }
136#  endif
137# elif defined(_MSC_VER)
138#  include <windows.h>
139#  undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
140#  ifdef USE_TRY_CATCH_FLAVOR
141#  else
142   LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
143   {
144      if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
145         ep->ContextRecord->Eip += 3 + 3 + 6;
146         return EXCEPTION_CONTINUE_EXECUTION;
147      }
148      return EXCEPTION_CONTINUE_SEARCH;
149   }
150#  endif
151# endif
152#endif
153
154
155void FLAC__cpu_info(FLAC__CPUInfo *info)
156{
157/*
158 * IA32-specific
159 */
160#ifdef FLAC__CPU_IA32
161   info->type = FLAC__CPUINFO_TYPE_IA32;
162#if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
163   info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
164   info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
165   info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
166   info->data.ia32.cmov = false;
167   info->data.ia32.mmx = false;
168   info->data.ia32.fxsr = false;
169   info->data.ia32.sse = false;
170   info->data.ia32.sse2 = false;
171   info->data.ia32.sse3 = false;
172   info->data.ia32.ssse3 = false;
173   info->data.ia32._3dnow = false;
174   info->data.ia32.ext3dnow = false;
175   info->data.ia32.extmmx = false;
176   if(info->data.ia32.cpuid) {
177      /* http://www.sandpile.org/ia32/cpuid.htm */
178      FLAC__uint32 flags_edx, flags_ecx;
179      FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
180      info->data.ia32.cmov  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
181      info->data.ia32.mmx   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX  )? true : false;
182      info->data.ia32.fxsr  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
183      info->data.ia32.sse   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE  )? true : false;
184      info->data.ia32.sse2  = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
185      info->data.ia32.sse3  = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
186      info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
187
188#ifdef FLAC__USE_3DNOW
189      flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
190      info->data.ia32._3dnow   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW   )? true : false;
191      info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
192      info->data.ia32.extmmx   = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX  )? true : false;
193#else
194      info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
195#endif
196
197#ifdef DEBUG
198      fprintf(stderr, "CPU info (IA-32):\n");
199      fprintf(stderr, "  CPUID ...... %c\n", info->data.ia32.cpuid   ? 'Y' : 'n');
200      fprintf(stderr, "  BSWAP ...... %c\n", info->data.ia32.bswap   ? 'Y' : 'n');
201      fprintf(stderr, "  CMOV ....... %c\n", info->data.ia32.cmov    ? 'Y' : 'n');
202      fprintf(stderr, "  MMX ........ %c\n", info->data.ia32.mmx     ? 'Y' : 'n');
203      fprintf(stderr, "  FXSR ....... %c\n", info->data.ia32.fxsr    ? 'Y' : 'n');
204      fprintf(stderr, "  SSE ........ %c\n", info->data.ia32.sse     ? 'Y' : 'n');
205      fprintf(stderr, "  SSE2 ....... %c\n", info->data.ia32.sse2    ? 'Y' : 'n');
206      fprintf(stderr, "  SSE3 ....... %c\n", info->data.ia32.sse3    ? 'Y' : 'n');
207      fprintf(stderr, "  SSSE3 ...... %c\n", info->data.ia32.ssse3   ? 'Y' : 'n');
208      fprintf(stderr, "  3DNow! ..... %c\n", info->data.ia32._3dnow  ? 'Y' : 'n');
209      fprintf(stderr, "  3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
210      fprintf(stderr, "  3DNow!-MMX . %c\n", info->data.ia32.extmmx  ? 'Y' : 'n');
211#endif
212
213      /*
214       * now have to check for OS support of SSE/SSE2
215       */
216      if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
217#if defined FLAC__NO_SSE_OS
218         /* assume user knows better than us; turn it off */
219         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
220#elif defined FLAC__SSE_OS
221         /* assume user knows better than us; leave as detected above */
222#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
223         int sse = 0;
224         size_t len;
225         /* at least one of these must work: */
226         len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
227         len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse"   , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
228         if(!sse)
229            info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
230#elif defined(__NetBSD__) || defined (__OpenBSD__)
231# if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
232         int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
233         size_t len = sizeof(val);
234         if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
235            info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
236         else { /* double-check SSE2 */
237            mib[1] = CPU_SSE2;
238            len = sizeof(val);
239            if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
240               info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
241         }
242# else
243         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
244# endif
245#elif defined(__linux__)
246         int sse = 0;
247         struct sigaction sigill_save;
248#ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
249         if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
250#else
251         struct sigaction sigill_sse;
252         sigill_sse.sa_sigaction = sigill_handler_sse_os;
253         __sigemptyset(&sigill_sse.sa_mask);
254         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 */
255         if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
256#endif
257         {
258            /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
259            /* see sigill_handler_sse_os() for an explanation of the following: */
260            asm volatile (
261               "xorl %0,%0\n\t"          /* for some reason, still need to do this to clear 'sse' var */
262               "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
263               "incl %0\n\t"             /* SIGILL handler will jump over this */
264               /* landing zone */
265               "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
266               "nop\n\t"
267               "nop\n\t"
268               "nop\n\t"
269               "nop\n\t"
270               "nop\n\t"
271               "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
272               "nop\n\t"
273               "nop"     /* SIGILL jump lands here if "inc" is 1 byte */
274               : "=r"(sse)
275               : "r"(sse)
276            );
277
278            sigaction(SIGILL, &sigill_save, NULL);
279         }
280
281         if(!sse)
282            info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
283#elif defined(_MSC_VER)
284# ifdef USE_TRY_CATCH_FLAVOR
285         _try {
286            __asm {
287#  if _MSC_VER <= 1200
288               /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
289               _emit 0x0F
290               _emit 0x57
291               _emit 0xC0
292#  else
293               xorps xmm0,xmm0
294#  endif
295            }
296         }
297         _except(EXCEPTION_EXECUTE_HANDLER) {
298            if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
299               info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
300         }
301# else
302         int sse = 0;
303         LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
304         /* see GCC version above for explanation */
305         /*  http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
306         /*  http://www.codeproject.com/cpp/gccasm.asp */
307         /*  http://www.hick.org/~mmiller/msvc_inline_asm.html */
308         __asm {
309#  if _MSC_VER <= 1200
310            /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
311            _emit 0x0F
312            _emit 0x57
313            _emit 0xC0
314#  else
315            xorps xmm0,xmm0
316#  endif
317            inc sse
318            nop
319            nop
320            nop
321            nop
322            nop
323            nop
324            nop
325            nop
326            nop
327         }
328         SetUnhandledExceptionFilter(save);
329         if(!sse)
330            info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
331# endif
332#else
333         /* no way to test, disable to be safe */
334         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
335#endif
336#ifdef DEBUG
337      fprintf(stderr, "  SSE OS sup . %c\n", info->data.ia32.sse     ? 'Y' : 'n');
338#endif
339
340      }
341   }
342#else
343   info->use_asm = false;
344#endif
345
346/*
347 * PPC-specific
348 */
349#elif defined FLAC__CPU_PPC
350   info->type = FLAC__CPUINFO_TYPE_PPC;
351# if !defined FLAC__NO_ASM
352   info->use_asm = true;
353#  ifdef FLAC__USE_ALTIVEC
354#   if defined FLAC__SYS_DARWIN
355   {
356      int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
357      size_t len = sizeof(val);
358      info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
359   }
360   {
361      host_basic_info_data_t hostInfo;
362      mach_msg_type_number_t infoCount;
363
364      infoCount = HOST_BASIC_INFO_COUNT;
365      host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
366
367      info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
368   }
369#   else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
370   {
371      /* no Darwin, do it the brute-force way */
372      /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
373      info->data.ppc.altivec = 0;
374      info->data.ppc.ppc64 = 0;
375
376      signal (SIGILL, sigill_handler);
377      canjump = 0;
378      if (!sigsetjmp (jmpbuf, 1)) {
379         canjump = 1;
380
381         asm volatile (
382            "mtspr 256, %0\n\t"
383            "vand %%v0, %%v0, %%v0"
384            :
385            : "r" (-1)
386         );
387
388         info->data.ppc.altivec = 1;
389      }
390      canjump = 0;
391      if (!sigsetjmp (jmpbuf, 1)) {
392         int x = 0;
393         canjump = 1;
394
395         /* PPC64 hardware implements the cntlzd instruction */
396         asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
397
398         info->data.ppc.ppc64 = 1;
399      }
400      signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
401   }
402#   endif
403#  else /* !FLAC__USE_ALTIVEC */
404   info->data.ppc.altivec = 0;
405   info->data.ppc.ppc64 = 0;
406#  endif
407# else
408   info->use_asm = false;
409# endif
410
411/*
412 * unknown CPI
413 */
414#else
415   info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
416   info->use_asm = false;
417#endif
418}
src/lib/libflac/libflac/bitmath.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include "private/bitmath.h"
37#include "flac/assert.h"
38
39/* An example of what FLAC__bitmath_ilog2() computes:
40 *
41 * ilog2( 0) = assertion failure
42 * ilog2( 1) = 0
43 * ilog2( 2) = 1
44 * ilog2( 3) = 1
45 * ilog2( 4) = 2
46 * ilog2( 5) = 2
47 * ilog2( 6) = 2
48 * ilog2( 7) = 2
49 * ilog2( 8) = 3
50 * ilog2( 9) = 3
51 * ilog2(10) = 3
52 * ilog2(11) = 3
53 * ilog2(12) = 3
54 * ilog2(13) = 3
55 * ilog2(14) = 3
56 * ilog2(15) = 3
57 * ilog2(16) = 4
58 * ilog2(17) = 4
59 * ilog2(18) = 4
60 */
61unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
62{
63   unsigned l = 0;
64   FLAC__ASSERT(v > 0);
65   while(v >>= 1)
66      l++;
67   return l;
68}
69
70unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
71{
72   unsigned l = 0;
73   FLAC__ASSERT(v > 0);
74   while(v >>= 1)
75      l++;
76   return l;
77}
78
79/* An example of what FLAC__bitmath_silog2() computes:
80 *
81 * silog2(-10) = 5
82 * silog2(- 9) = 5
83 * silog2(- 8) = 4
84 * silog2(- 7) = 4
85 * silog2(- 6) = 4
86 * silog2(- 5) = 4
87 * silog2(- 4) = 3
88 * silog2(- 3) = 3
89 * silog2(- 2) = 2
90 * silog2(- 1) = 2
91 * silog2(  0) = 0
92 * silog2(  1) = 2
93 * silog2(  2) = 3
94 * silog2(  3) = 3
95 * silog2(  4) = 4
96 * silog2(  5) = 4
97 * silog2(  6) = 4
98 * silog2(  7) = 4
99 * silog2(  8) = 5
100 * silog2(  9) = 5
101 * silog2( 10) = 5
102 */
103unsigned FLAC__bitmath_silog2(int v)
104{
105   while(1) {
106      if(v == 0) {
107         return 0;
108      }
109      else if(v > 0) {
110         unsigned l = 0;
111         while(v) {
112            l++;
113            v >>= 1;
114         }
115         return l+1;
116      }
117      else if(v == -1) {
118         return 2;
119      }
120      else {
121         v++;
122         v = -v;
123      }
124   }
125}
126
127unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
128{
129   while(1) {
130      if(v == 0) {
131         return 0;
132      }
133      else if(v > 0) {
134         unsigned l = 0;
135         while(v) {
136            l++;
137            v >>= 1;
138         }
139         return l+1;
140      }
141      else if(v == -1) {
142         return 2;
143      }
144      else {
145         v++;
146         v = -v;
147      }
148   }
149}
src/lib/libflac/libflac/format.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include <stdio.h>
37#include <stdlib.h> /* for qsort() */
38#include <string.h> /* for memset() */
39#include "flac/assert.h"
40#include "flac/format.h"
41#include "private/format.h"
42
43#ifndef FLaC__INLINE
44#define FLaC__INLINE
45#endif
46
47#ifdef min
48#undef min
49#endif
50#define min(a,b) ((a)<(b)?(a):(b))
51
52/* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
53#ifdef _MSC_VER
54#define FLAC__U64L(x) x
55#else
56#define FLAC__U64L(x) x##LLU
57#endif
58
59/* VERSION should come from configure */
60FLAC_API const char *FLAC__VERSION_STRING = VERSION;
61
62#if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
63/* yet one more hack because of MSVC6: */
64FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
65#else
66FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
67#endif
68
69FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
70FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
71FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
72
73FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
74FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
75FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
76FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
77FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
78FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
79FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
80FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
81FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
82
83FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
84
85FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
86FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
87FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
88
89FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
90
91FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
92FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
93
94FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
95FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
96FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
97
98FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
99FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
100FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
101FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
102FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
103FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
104FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
105
106FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
107FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
108FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
109FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
110FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
111
112FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
113FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
114FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
115FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
116FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
117FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
118FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
119FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
120
121FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
122FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
123FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
124
125FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
126FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
127FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
128FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
129FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
130FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
131FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
132FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
133FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
134FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
135
136FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
137
138FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
139FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
140FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
141FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
142FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
143
144FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
145FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
146
147FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
148   "PARTITIONED_RICE",
149   "PARTITIONED_RICE2"
150};
151
152FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
153FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
154
155FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
156FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
157FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
158
159FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
160FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
161FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
162FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
163
164FLAC_API const char * const FLAC__SubframeTypeString[] = {
165   "CONSTANT",
166   "VERBATIM",
167   "FIXED",
168   "LPC"
169};
170
171FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
172   "INDEPENDENT",
173   "LEFT_SIDE",
174   "RIGHT_SIDE",
175   "MID_SIDE"
176};
177
178FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
179   "FRAME_NUMBER_TYPE_FRAME_NUMBER",
180   "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
181};
182
183FLAC_API const char * const FLAC__MetadataTypeString[] = {
184   "STREAMINFO",
185   "PADDING",
186   "APPLICATION",
187   "SEEKTABLE",
188   "VORBIS_COMMENT",
189   "CUESHEET",
190   "PICTURE"
191};
192
193FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
194   "Other",
195   "32x32 pixels 'file icon' (PNG only)",
196   "Other file icon",
197   "Cover (front)",
198   "Cover (back)",
199   "Leaflet page",
200   "Media (e.g. label side of CD)",
201   "Lead artist/lead performer/soloist",
202   "Artist/performer",
203   "Conductor",
204   "Band/Orchestra",
205   "Composer",
206   "Lyricist/text writer",
207   "Recording Location",
208   "During recording",
209   "During performance",
210   "Movie/video screen capture",
211   "A bright coloured fish",
212   "Illustration",
213   "Band/artist logotype",
214   "Publisher/Studio logotype"
215};
216
217FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
218{
219   if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
220      return false;
221   }
222   else
223      return true;
224}
225
226FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
227{
228   if(
229      !FLAC__format_sample_rate_is_valid(sample_rate) ||
230      (
231         sample_rate >= (1u << 16) &&
232         !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
233      )
234   ) {
235      return false;
236   }
237   else
238      return true;
239}
240
241/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
242FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
243{
244   unsigned i;
245   FLAC__uint64 prev_sample_number = 0;
246   FLAC__bool got_prev = false;
247
248   FLAC__ASSERT(0 != seek_table);
249
250   for(i = 0; i < seek_table->num_points; i++) {
251      if(got_prev) {
252         if(
253            seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
254            seek_table->points[i].sample_number <= prev_sample_number
255         )
256            return false;
257      }
258      prev_sample_number = seek_table->points[i].sample_number;
259      got_prev = true;
260   }
261
262   return true;
263}
264
265/* used as the sort predicate for qsort() */
266static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
267{
268   /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
269   if(l->sample_number == r->sample_number)
270      return 0;
271   else if(l->sample_number < r->sample_number)
272      return -1;
273   else
274      return 1;
275}
276
277/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
278FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
279{
280   unsigned i, j;
281   FLAC__bool first;
282
283   FLAC__ASSERT(0 != seek_table);
284
285   /* sort the seekpoints */
286   qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
287
288   /* uniquify the seekpoints */
289   first = true;
290   for(i = j = 0; i < seek_table->num_points; i++) {
291      if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
292         if(!first) {
293            if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
294               continue;
295         }
296      }
297      first = false;
298      seek_table->points[j++] = seek_table->points[i];
299   }
300
301   for(i = j; i < seek_table->num_points; i++) {
302      seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
303      seek_table->points[i].stream_offset = 0;
304      seek_table->points[i].frame_samples = 0;
305   }
306
307   return j;
308}
309
310/*
311 * also disallows non-shortest-form encodings, c.f.
312 *   http://www.unicode.org/versions/corrigendum1.html
313 * and a more clear explanation at the end of this section:
314 *   http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
315 */
316static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
317{
318   FLAC__ASSERT(0 != utf8);
319   if ((utf8[0] & 0x80) == 0) {
320      return 1;
321   }
322   else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
323      if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
324         return 0;
325      return 2;
326   }
327   else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
328      if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
329         return 0;
330      /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
331      if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
332         return 0;
333      if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
334         return 0;
335      return 3;
336   }
337   else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
338      if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
339         return 0;
340      return 4;
341   }
342   else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
343      if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
344         return 0;
345      return 5;
346   }
347   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) {
348      if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
349         return 0;
350      return 6;
351   }
352   else {
353      return 0;
354   }
355}
356
357FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
358{
359   char c;
360   for(c = *name; c; c = *(++name))
361      if(c < 0x20 || c == 0x3d || c > 0x7d)
362         return false;
363   return true;
364}
365
366FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
367{
368   if(length == (unsigned)(-1)) {
369      while(*value) {
370         unsigned n = utf8len_(value);
371         if(n == 0)
372            return false;
373         value += n;
374      }
375   }
376   else {
377      const FLAC__byte *end = value + length;
378      while(value < end) {
379         unsigned n = utf8len_(value);
380         if(n == 0)
381            return false;
382         value += n;
383      }
384      if(value != end)
385         return false;
386   }
387   return true;
388}
389
390FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
391{
392   const FLAC__byte *s, *end;
393
394   for(s = entry, end = s + length; s < end && *s != '='; s++) {
395      if(*s < 0x20 || *s > 0x7D)
396         return false;
397   }
398   if(s == end)
399      return false;
400
401   s++; /* skip '=' */
402
403   while(s < end) {
404      unsigned n = utf8len_(s);
405      if(n == 0)
406         return false;
407      s += n;
408   }
409   if(s != end)
410      return false;
411
412   return true;
413}
414
415/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
416FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
417{
418   unsigned i, j;
419
420   if(check_cd_da_subset) {
421      if(cue_sheet->lead_in < 2 * 44100) {
422         if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
423         return false;
424      }
425      if(cue_sheet->lead_in % 588 != 0) {
426         if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
427         return false;
428      }
429   }
430
431   if(cue_sheet->num_tracks == 0) {
432      if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
433      return false;
434   }
435
436   if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
437      if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
438      return false;
439   }
440
441   for(i = 0; i < cue_sheet->num_tracks; i++) {
442      if(cue_sheet->tracks[i].number == 0) {
443         if(violation) *violation = "cue sheet may not have a track number 0";
444         return false;
445      }
446
447      if(check_cd_da_subset) {
448         if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
449            if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
450            return false;
451         }
452      }
453
454      if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
455         if(violation) {
456            if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
457               *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
458            else
459               *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
460         }
461         return false;
462      }
463
464      if(i < cue_sheet->num_tracks - 1) {
465         if(cue_sheet->tracks[i].num_indices == 0) {
466            if(violation) *violation = "cue sheet track must have at least one index point";
467            return false;
468         }
469
470         if(cue_sheet->tracks[i].indices[0].number > 1) {
471            if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
472            return false;
473         }
474      }
475
476      for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
477         if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
478            if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
479            return false;
480         }
481
482         if(j > 0) {
483            if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
484               if(violation) *violation = "cue sheet track index numbers must increase by 1";
485               return false;
486            }
487         }
488      }
489   }
490
491   return true;
492}
493
494/* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
495FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
496{
497   char *p;
498   FLAC__byte *b;
499
500   for(p = picture->mime_type; *p; p++) {
501      if(*p < 0x20 || *p > 0x7e) {
502         if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
503         return false;
504      }
505   }
506
507   for(b = picture->description; *b; ) {
508      unsigned n = utf8len_(b);
509      if(n == 0) {
510         if(violation) *violation = "description string must be valid UTF-8";
511         return false;
512      }
513      b += n;
514   }
515
516   return true;
517}
518
519/*
520 * These routines are private to libFLAC
521 */
522unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
523{
524   return
525      FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
526         FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
527         blocksize,
528         predictor_order
529      );
530}
531
532unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
533{
534   unsigned max_rice_partition_order = 0;
535   while(!(blocksize & 1)) {
536      max_rice_partition_order++;
537      blocksize >>= 1;
538   }
539   return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
540}
541
542unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
543{
544   unsigned max_rice_partition_order = limit;
545
546   while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
547      max_rice_partition_order--;
548
549   FLAC__ASSERT(
550      (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
551      (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
552   );
553
554   return max_rice_partition_order;
555}
556
557void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
558{
559   FLAC__ASSERT(0 != object);
560
561   object->parameters = 0;
562   object->raw_bits = 0;
563   object->capacity_by_order = 0;
564}
565
566void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
567{
568   FLAC__ASSERT(0 != object);
569
570   if(0 != object->parameters)
571      free(object->parameters);
572   if(0 != object->raw_bits)
573      free(object->raw_bits);
574   FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
575}
576
577FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
578{
579   FLAC__ASSERT(0 != object);
580
581   FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
582
583   if(object->capacity_by_order < max_partition_order) {
584      if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
585         return false;
586      if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
587         return false;
588      memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
589      object->capacity_by_order = max_partition_order;
590   }
591
592   return true;
593}
src/lib/libflac/libflac/stream_encoder.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include <limits.h>
37#include <stdio.h>
38#include <stdlib.h> /* for malloc() */
39#include <string.h> /* for memcpy() */
40#include <sys/types.h> /* for off_t */
41#if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
42#if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
43#define fseeko fseek
44#define ftello ftell
45#endif
46#endif
47#include "flac/assert.h"
48#include "flac/stream_decoder.h"
49#include "share/alloc.h"
50#include "protected/stream_encoder.h"
51#include "private/bitwriter.h"
52#include "private/bitmath.h"
53#include "private/crc.h"
54#include "private/cpu.h"
55#include "private/fixed.h"
56#include "private/format.h"
57#include "private/lpc.h"
58#include "private/md5.h"
59#include "private/memory.h"
60#if FLAC__HAS_OGG
61#include "private/ogg_helper.h"
62#include "private/ogg_mapping.h"
63#endif
64#include "private/stream_encoder_framing.h"
65#include "private/window.h"
66
67#ifndef FLaC__INLINE
68#define FLaC__INLINE
69#endif
70
71#ifdef min
72#undef min
73#endif
74#define min(x,y) ((x)<(y)?(x):(y))
75
76#ifdef max
77#undef max
78#endif
79#define max(x,y) ((x)>(y)?(x):(y))
80
81/* Exact Rice codeword length calculation is off by default.  The simple
82 * (and fast) estimation (of how many bits a residual value will be
83 * encoded with) in this encoder is very good, almost always yielding
84 * compression within 0.1% of exact calculation.
85 */
86#undef EXACT_RICE_BITS_CALCULATION
87/* Rice parameter searching is off by default.  The simple (and fast)
88 * parameter estimation in this encoder is very good, almost always
89 * yielding compression within 0.1% of the optimal parameters.
90 */
91#undef ENABLE_RICE_PARAMETER_SEARCH
92
93
94typedef struct {
95   FLAC__int32 *data[FLAC__MAX_CHANNELS];
96   unsigned size; /* of each data[] in samples */
97   unsigned tail;
98} verify_input_fifo;
99
100typedef struct {
101   const FLAC__byte *data;
102   unsigned capacity;
103   unsigned bytes;
104} verify_output;
105
106typedef enum {
107   ENCODER_IN_MAGIC = 0,
108   ENCODER_IN_METADATA = 1,
109   ENCODER_IN_AUDIO = 2
110} EncoderStateHint;
111
112static struct CompressionLevels {
113   FLAC__bool do_mid_side_stereo;
114   FLAC__bool loose_mid_side_stereo;
115   unsigned max_lpc_order;
116   unsigned qlp_coeff_precision;
117   FLAC__bool do_qlp_coeff_prec_search;
118   FLAC__bool do_escape_coding;
119   FLAC__bool do_exhaustive_model_search;
120   unsigned min_residual_partition_order;
121   unsigned max_residual_partition_order;
122   unsigned rice_parameter_search_dist;
123} compression_levels_[] = {
124   { false, false,  0, 0, false, false, false, 0, 3, 0 },
125   { true , true ,  0, 0, false, false, false, 0, 3, 0 },
126   { true , false,  0, 0, false, false, false, 0, 3, 0 },
127   { false, false,  6, 0, false, false, false, 0, 4, 0 },
128   { true , true ,  8, 0, false, false, false, 0, 4, 0 },
129   { true , false,  8, 0, false, false, false, 0, 5, 0 },
130   { true , false,  8, 0, false, false, false, 0, 6, 0 },
131   { true , false,  8, 0, false, false, true , 0, 6, 0 },
132   { true , false, 12, 0, false, false, true , 0, 6, 0 }
133};
134
135
136/***********************************************************************
137 *
138 * Private class method prototypes
139 *
140 ***********************************************************************/
141
142static void set_defaults_(FLAC__StreamEncoder *encoder);
143static void free_(FLAC__StreamEncoder *encoder);
144static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
145static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
146static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
147static void update_metadata_(const FLAC__StreamEncoder *encoder);
148#if FLAC__HAS_OGG
149static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
150#endif
151static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
152static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
153
154static FLAC__bool process_subframe_(
155   FLAC__StreamEncoder *encoder,
156   unsigned min_partition_order,
157   unsigned max_partition_order,
158   const FLAC__FrameHeader *frame_header,
159   unsigned subframe_bps,
160   const FLAC__int32 integer_signal[],
161   FLAC__Subframe *subframe[2],
162   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
163   FLAC__int32 *residual[2],
164   unsigned *best_subframe,
165   unsigned *best_bits
166);
167
168static FLAC__bool add_subframe_(
169   FLAC__StreamEncoder *encoder,
170   unsigned blocksize,
171   unsigned subframe_bps,
172   const FLAC__Subframe *subframe,
173   FLAC__BitWriter *frame
174);
175
176static unsigned evaluate_constant_subframe_(
177   FLAC__StreamEncoder *encoder,
178   const FLAC__int32 signal,
179   unsigned blocksize,
180   unsigned subframe_bps,
181   FLAC__Subframe *subframe
182);
183
184static unsigned evaluate_fixed_subframe_(
185   FLAC__StreamEncoder *encoder,
186   const FLAC__int32 signal[],
187   FLAC__int32 residual[],
188   FLAC__uint64 abs_residual_partition_sums[],
189   unsigned raw_bits_per_partition[],
190   unsigned blocksize,
191   unsigned subframe_bps,
192   unsigned order,
193   unsigned rice_parameter,
194   unsigned rice_parameter_limit,
195   unsigned min_partition_order,
196   unsigned max_partition_order,
197   FLAC__bool do_escape_coding,
198   unsigned rice_parameter_search_dist,
199   FLAC__Subframe *subframe,
200   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
201);
202
203#ifndef FLAC__INTEGER_ONLY_LIBRARY
204static unsigned evaluate_lpc_subframe_(
205   FLAC__StreamEncoder *encoder,
206   const FLAC__int32 signal[],
207   FLAC__int32 residual[],
208   FLAC__uint64 abs_residual_partition_sums[],
209   unsigned raw_bits_per_partition[],
210   const FLAC__real lp_coeff[],
211   unsigned blocksize,
212   unsigned subframe_bps,
213   unsigned order,
214   unsigned qlp_coeff_precision,
215   unsigned rice_parameter,
216   unsigned rice_parameter_limit,
217   unsigned min_partition_order,
218   unsigned max_partition_order,
219   FLAC__bool do_escape_coding,
220   unsigned rice_parameter_search_dist,
221   FLAC__Subframe *subframe,
222   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
223);
224#endif
225
226static unsigned evaluate_verbatim_subframe_(
227   FLAC__StreamEncoder *encoder,
228   const FLAC__int32 signal[],
229   unsigned blocksize,
230   unsigned subframe_bps,
231   FLAC__Subframe *subframe
232);
233
234static unsigned find_best_partition_order_(
235   struct FLAC__StreamEncoderPrivate *private_,
236   const FLAC__int32 residual[],
237   FLAC__uint64 abs_residual_partition_sums[],
238   unsigned raw_bits_per_partition[],
239   unsigned residual_samples,
240   unsigned predictor_order,
241   unsigned rice_parameter,
242   unsigned rice_parameter_limit,
243   unsigned min_partition_order,
244   unsigned max_partition_order,
245   unsigned bps,
246   FLAC__bool do_escape_coding,
247   unsigned rice_parameter_search_dist,
248   FLAC__EntropyCodingMethod *best_ecm
249);
250
251static void precompute_partition_info_sums_(
252   const FLAC__int32 residual[],
253   FLAC__uint64 abs_residual_partition_sums[],
254   unsigned residual_samples,
255   unsigned predictor_order,
256   unsigned min_partition_order,
257   unsigned max_partition_order,
258   unsigned bps
259);
260
261static void precompute_partition_info_escapes_(
262   const FLAC__int32 residual[],
263   unsigned raw_bits_per_partition[],
264   unsigned residual_samples,
265   unsigned predictor_order,
266   unsigned min_partition_order,
267   unsigned max_partition_order
268);
269
270static FLAC__bool set_partitioned_rice_(
271#ifdef EXACT_RICE_BITS_CALCULATION
272   const FLAC__int32 residual[],
273#endif
274   const FLAC__uint64 abs_residual_partition_sums[],
275   const unsigned raw_bits_per_partition[],
276   const unsigned residual_samples,
277   const unsigned predictor_order,
278   const unsigned suggested_rice_parameter,
279   const unsigned rice_parameter_limit,
280   const unsigned rice_parameter_search_dist,
281   const unsigned partition_order,
282   const FLAC__bool search_for_escapes,
283   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
284   unsigned *bits
285);
286
287static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
288
289/* verify-related routines: */
290static void append_to_verify_fifo_(
291   verify_input_fifo *fifo,
292   const FLAC__int32 * const input[],
293   unsigned input_offset,
294   unsigned channels,
295   unsigned wide_samples
296);
297
298static void append_to_verify_fifo_interleaved_(
299   verify_input_fifo *fifo,
300   const FLAC__int32 input[],
301   unsigned input_offset,
302   unsigned channels,
303   unsigned wide_samples
304);
305
306static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
307static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
308static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
309static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
310
311static FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
312static FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
313static FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
314static FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
315static FILE *get_binary_stdout_(void);
316
317
318/***********************************************************************
319 *
320 * Private class data
321 *
322 ***********************************************************************/
323
324typedef struct FLAC__StreamEncoderPrivate {
325   unsigned input_capacity;                          /* current size (in samples) of the signal and residual buffers */
326   FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS];  /* the integer version of the input signal */
327   FLAC__int32 *integer_signal_mid_side[2];          /* the integer version of the mid-side input signal (stereo only) */
328#ifndef FLAC__INTEGER_ONLY_LIBRARY
329   FLAC__real *real_signal[FLAC__MAX_CHANNELS];      /* (@@@ currently unused) the floating-point version of the input signal */
330   FLAC__real *real_signal_mid_side[2];              /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
331   FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
332   FLAC__real *windowed_signal;                      /* the integer_signal[] * current window[] */
333#endif
334   unsigned subframe_bps[FLAC__MAX_CHANNELS];        /* the effective bits per sample of the input signal (stream bps - wasted bits) */
335   unsigned subframe_bps_mid_side[2];                /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
336   FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
337   FLAC__int32 *residual_workspace_mid_side[2][2];
338   FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
339   FLAC__Subframe subframe_workspace_mid_side[2][2];
340   FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
341   FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
342   FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
343   FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
344   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
345   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
346   unsigned best_subframe[FLAC__MAX_CHANNELS];       /* index (0 or 1) into 2nd dimension of the above workspaces */
347   unsigned best_subframe_mid_side[2];
348   unsigned best_subframe_bits[FLAC__MAX_CHANNELS];  /* size in bits of the best subframe for each channel */
349   unsigned best_subframe_bits_mid_side[2];
350   FLAC__uint64 *abs_residual_partition_sums;        /* workspace where the sum of abs(candidate residual) for each partition is stored */
351   unsigned *raw_bits_per_partition;                 /* workspace where the sum of silog2(candidate residual) for each partition is stored */
352   FLAC__BitWriter *frame;                           /* the current frame being worked on */
353   unsigned loose_mid_side_stereo_frames;            /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
354   unsigned loose_mid_side_stereo_frame_count;       /* number of frames using the current channel assignment */
355   FLAC__ChannelAssignment last_channel_assignment;
356   FLAC__StreamMetadata streaminfo;                  /* scratchpad for STREAMINFO as it is built */
357   FLAC__StreamMetadata_SeekTable *seek_table;       /* pointer into encoder->protected_->metadata_ where the seek table is */
358   unsigned current_sample_number;
359   unsigned current_frame_number;
360   FLAC__MD5Context md5context;
361   FLAC__CPUInfo cpuinfo;
362#ifndef FLAC__INTEGER_ONLY_LIBRARY
363   unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
364#else
365   unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
366#endif
367#ifndef FLAC__INTEGER_ONLY_LIBRARY
368   void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
369   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[]);
370   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[]);
371   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[]);
372#endif
373   FLAC__bool use_wide_by_block;          /* use slow 64-bit versions of some functions because of the block size */
374   FLAC__bool use_wide_by_partition;      /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
375   FLAC__bool use_wide_by_order;          /* use slow 64-bit versions of some functions because of the lpc order */
376   FLAC__bool disable_constant_subframes;
377   FLAC__bool disable_fixed_subframes;
378   FLAC__bool disable_verbatim_subframes;
379#if FLAC__HAS_OGG
380   FLAC__bool is_ogg;
381#endif
382   FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
383   FLAC__StreamEncoderSeekCallback seek_callback;
384   FLAC__StreamEncoderTellCallback tell_callback;
385   FLAC__StreamEncoderWriteCallback write_callback;
386   FLAC__StreamEncoderMetadataCallback metadata_callback;
387   FLAC__StreamEncoderProgressCallback progress_callback;
388   void *client_data;
389   unsigned first_seekpoint_to_check;
390   FILE *file;                            /* only used when encoding to a file */
391   FLAC__uint64 bytes_written;
392   FLAC__uint64 samples_written;
393   unsigned frames_written;
394   unsigned total_frames_estimate;
395   /* unaligned (original) pointers to allocated data */
396   FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
397   FLAC__int32 *integer_signal_mid_side_unaligned[2];
398#ifndef FLAC__INTEGER_ONLY_LIBRARY
399   FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
400   FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
401   FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
402   FLAC__real *windowed_signal_unaligned;
403#endif
404   FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
405   FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
406   FLAC__uint64 *abs_residual_partition_sums_unaligned;
407   unsigned *raw_bits_per_partition_unaligned;
408   /*
409    * These fields have been moved here from private function local
410    * declarations merely to save stack space during encoding.
411    */
412#ifndef FLAC__INTEGER_ONLY_LIBRARY
413   FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
414#endif
415   FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
416   /*
417    * The data for the verify section
418    */
419   struct {
420      FLAC__StreamDecoder *decoder;
421      EncoderStateHint state_hint;
422      FLAC__bool needs_magic_hack;
423      verify_input_fifo input_fifo;
424      verify_output output;
425      struct {
426         FLAC__uint64 absolute_sample;
427         unsigned frame_number;
428         unsigned channel;
429         unsigned sample;
430         FLAC__int32 expected;
431         FLAC__int32 got;
432      } error_stats;
433   } verify;
434   FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
435} FLAC__StreamEncoderPrivate;
436
437/***********************************************************************
438 *
439 * Public static class data
440 *
441 ***********************************************************************/
442
443FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
444   "FLAC__STREAM_ENCODER_OK",
445   "FLAC__STREAM_ENCODER_UNINITIALIZED",
446   "FLAC__STREAM_ENCODER_OGG_ERROR",
447   "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
448   "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
449   "FLAC__STREAM_ENCODER_CLIENT_ERROR",
450   "FLAC__STREAM_ENCODER_IO_ERROR",
451   "FLAC__STREAM_ENCODER_FRAMING_ERROR",
452   "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
453};
454
455FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
456   "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
457   "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
458   "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
459   "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
460   "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
461   "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
462   "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
463   "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
464   "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
465   "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
466   "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
467   "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
468   "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
469   "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
470};
471
472FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
473   "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
474   "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
475   "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
476   "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
477};
478
479FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
480   "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
481   "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
482};
483
484FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
485   "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
486   "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
487   "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
488};
489
490FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
491   "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
492   "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
493   "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
494};
495
496/* Number of samples that will be overread to watch for end of stream.  By
497 * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
498 * always try to read blocksize+1 samples before encoding a block, so that
499 * even if the stream has a total sample count that is an integral multiple
500 * of the blocksize, we will still notice when we are encoding the last
501 * block.  This is needed, for example, to correctly set the end-of-stream
502 * marker in Ogg FLAC.
503 *
504 * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
505 * not really any reason to change it.
506 */
507static const unsigned OVERREAD_ = 1;
508
509/***********************************************************************
510 *
511 * Class constructor/destructor
512 *
513 */
514FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
515{
516   FLAC__StreamEncoder *encoder;
517   unsigned i;
518
519   FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
520
521   encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
522   if(encoder == 0) {
523      return 0;
524   }
525
526   encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
527   if(encoder->protected_ == 0) {
528      free(encoder);
529      return 0;
530   }
531
532   encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
533   if(encoder->private_ == 0) {
534      free(encoder->protected_);
535      free(encoder);
536      return 0;
537   }
538
539   encoder->private_->frame = FLAC__bitwriter_new();
540   if(encoder->private_->frame == 0) {
541      free(encoder->private_);
542      free(encoder->protected_);
543      free(encoder);
544      return 0;
545   }
546
547   encoder->private_->file = 0;
548
549   set_defaults_(encoder);
550
551   encoder->private_->is_being_deleted = false;
552
553   for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
554      encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
555      encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
556   }
557   for(i = 0; i < 2; i++) {
558      encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
559      encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
560   }
561   for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
562      encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
563      encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
564   }
565   for(i = 0; i < 2; i++) {
566      encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
567      encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
568   }
569
570   for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
571      FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
572      FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
573   }
574   for(i = 0; i < 2; i++) {
575      FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
576      FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
577   }
578   for(i = 0; i < 2; i++)
579      FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
580
581   encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
582
583   return encoder;
584}
585
586FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
587{
588   unsigned i;
589
590   FLAC__ASSERT(0 != encoder);
591   FLAC__ASSERT(0 != encoder->protected_);
592   FLAC__ASSERT(0 != encoder->private_);
593   FLAC__ASSERT(0 != encoder->private_->frame);
594
595   encoder->private_->is_being_deleted = true;
596
597   (void)FLAC__stream_encoder_finish(encoder);
598
599   if(0 != encoder->private_->verify.decoder)
600      FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
601
602   for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
603      FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
604      FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
605   }
606   for(i = 0; i < 2; i++) {
607      FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
608      FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
609   }
610   for(i = 0; i < 2; i++)
611      FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
612
613   FLAC__bitwriter_delete(encoder->private_->frame);
614   free(encoder->private_);
615   free(encoder->protected_);
616   free(encoder);
617}
618
619/***********************************************************************
620 *
621 * Public class methods
622 *
623 ***********************************************************************/
624
625static FLAC__StreamEncoderInitStatus init_stream_internal_(
626   FLAC__StreamEncoder *encoder,
627   FLAC__StreamEncoderReadCallback read_callback,
628   FLAC__StreamEncoderWriteCallback write_callback,
629   FLAC__StreamEncoderSeekCallback seek_callback,
630   FLAC__StreamEncoderTellCallback tell_callback,
631   FLAC__StreamEncoderMetadataCallback metadata_callback,
632   void *client_data,
633   FLAC__bool is_ogg
634)
635{
636   unsigned i;
637   FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
638
639   FLAC__ASSERT(0 != encoder);
640
641   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
642      return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
643
644#if !FLAC__HAS_OGG
645   if(is_ogg)
646      return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
647#endif
648
649   if(0 == write_callback || (seek_callback && 0 == tell_callback))
650      return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
651
652   if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
653      return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
654
655   if(encoder->protected_->channels != 2) {
656      encoder->protected_->do_mid_side_stereo = false;
657      encoder->protected_->loose_mid_side_stereo = false;
658   }
659   else if(!encoder->protected_->do_mid_side_stereo)
660      encoder->protected_->loose_mid_side_stereo = false;
661
662   if(encoder->protected_->bits_per_sample >= 32)
663      encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
664
665   if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
666      return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
667
668   if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
669      return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
670
671   if(encoder->protected_->blocksize == 0) {
672      if(encoder->protected_->max_lpc_order == 0)
673         encoder->protected_->blocksize = 1152;
674      else
675         encoder->protected_->blocksize = 4096;
676   }
677
678   if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
679      return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
680
681   if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
682      return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
683
684   if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
685      return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
686
687   if(encoder->protected_->qlp_coeff_precision == 0) {
688      if(encoder->protected_->bits_per_sample < 16) {
689         /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
690         /* @@@ until then we'll make a guess */
691         encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
692      }
693      else if(encoder->protected_->bits_per_sample == 16) {
694         if(encoder->protected_->blocksize <= 192)
695            encoder->protected_->qlp_coeff_precision = 7;
696         else if(encoder->protected_->blocksize <= 384)
697            encoder->protected_->qlp_coeff_precision = 8;
698         else if(encoder->protected_->blocksize <= 576)
699            encoder->protected_->qlp_coeff_precision = 9;
700         else if(encoder->protected_->blocksize <= 1152)
701            encoder->protected_->qlp_coeff_precision = 10;
702         else if(encoder->protected_->blocksize <= 2304)
703            encoder->protected_->qlp_coeff_precision = 11;
704         else if(encoder->protected_->blocksize <= 4608)
705            encoder->protected_->qlp_coeff_precision = 12;
706         else
707            encoder->protected_->qlp_coeff_precision = 13;
708      }
709      else {
710         if(encoder->protected_->blocksize <= 384)
711            encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
712         else if(encoder->protected_->blocksize <= 1152)
713            encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
714         else
715            encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
716      }
717      FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
718   }
719   else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
720      return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
721
722   if(encoder->protected_->streamable_subset) {
723      if(
724         encoder->protected_->blocksize != 192 &&
725         encoder->protected_->blocksize != 576 &&
726         encoder->protected_->blocksize != 1152 &&
727         encoder->protected_->blocksize != 2304 &&
728         encoder->protected_->blocksize != 4608 &&
729         encoder->protected_->blocksize != 256 &&
730         encoder->protected_->blocksize != 512 &&
731         encoder->protected_->blocksize != 1024 &&
732         encoder->protected_->blocksize != 2048 &&
733         encoder->protected_->blocksize != 4096 &&
734         encoder->protected_->blocksize != 8192 &&
735         encoder->protected_->blocksize != 16384
736      )
737         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
738      if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
739         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
740      if(
741         encoder->protected_->bits_per_sample != 8 &&
742         encoder->protected_->bits_per_sample != 12 &&
743         encoder->protected_->bits_per_sample != 16 &&
744         encoder->protected_->bits_per_sample != 20 &&
745         encoder->protected_->bits_per_sample != 24
746      )
747         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
748      if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
749         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
750      if(
751         encoder->protected_->sample_rate <= 48000 &&
752         (
753            encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
754            encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
755         )
756      ) {
757         return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
758      }
759   }
760
761   if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
762      encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
763   if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
764      encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
765
766#if FLAC__HAS_OGG
767   /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
768   if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
769      unsigned i;
770      for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
771         if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
772            FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
773            for( ; i > 0; i--)
774               encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
775            encoder->protected_->metadata[0] = vc;
776            break;
777         }
778      }
779   }
780#endif
781   /* keep track of any SEEKTABLE block */
782   if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
783      unsigned i;
784      for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
785         if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
786            encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
787            break; /* take only the first one */
788         }
789      }
790   }
791
792   /* validate metadata */
793   if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
794      return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
795   metadata_has_seektable = false;
796   metadata_has_vorbis_comment = false;
797   metadata_picture_has_type1 = false;
798   metadata_picture_has_type2 = false;
799   for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
800      const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
801      if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
802         return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
803      else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
804         if(metadata_has_seektable) /* only one is allowed */
805            return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
806         metadata_has_seektable = true;
807         if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
808            return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
809      }
810      else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
811         if(metadata_has_vorbis_comment) /* only one is allowed */
812            return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
813         metadata_has_vorbis_comment = true;
814      }
815      else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
816         if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
817            return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
818      }
819      else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
820         if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
821            return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
822         if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
823            if(metadata_picture_has_type1) /* there should only be 1 per stream */
824               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
825            metadata_picture_has_type1 = true;
826            /* standard icon must be 32x32 pixel PNG */
827            if(
828               m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
829               (
830                  (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
831                  m->data.picture.width != 32 ||
832                  m->data.picture.height != 32
833               )
834            )
835               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
836         }
837         else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
838            if(metadata_picture_has_type2) /* there should only be 1 per stream */
839               return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
840            metadata_picture_has_type2 = true;
841         }
842      }
843   }
844
845   encoder->private_->input_capacity = 0;
846   for(i = 0; i < encoder->protected_->channels; i++) {
847      encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
848#ifndef FLAC__INTEGER_ONLY_LIBRARY
849      encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
850#endif
851   }
852   for(i = 0; i < 2; i++) {
853      encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
854#ifndef FLAC__INTEGER_ONLY_LIBRARY
855      encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
856#endif
857   }
858#ifndef FLAC__INTEGER_ONLY_LIBRARY
859   for(i = 0; i < encoder->protected_->num_apodizations; i++)
860      encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
861   encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
862#endif
863   for(i = 0; i < encoder->protected_->channels; i++) {
864      encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
865      encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
866      encoder->private_->best_subframe[i] = 0;
867   }
868   for(i = 0; i < 2; i++) {
869      encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
870      encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
871      encoder->private_->best_subframe_mid_side[i] = 0;
872   }
873   encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
874   encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
875#ifndef FLAC__INTEGER_ONLY_LIBRARY
876   encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
877#else
878   /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
879   /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
880   FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
881   FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
882   FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
883   FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
884   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);
885#endif
886   if(encoder->private_->loose_mid_side_stereo_frames == 0)
887      encoder->private_->loose_mid_side_stereo_frames = 1;
888   encoder->private_->loose_mid_side_stereo_frame_count = 0;
889   encoder->private_->current_sample_number = 0;
890   encoder->private_->current_frame_number = 0;
891
892   encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
893   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? */
894   encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
895
896   /*
897    * get the CPU info and set the function pointers
898    */
899   FLAC__cpu_info(&encoder->private_->cpuinfo);
900   /* first default to the non-asm routines */
901#ifndef FLAC__INTEGER_ONLY_LIBRARY
902   encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
903#endif
904   encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
905#ifndef FLAC__INTEGER_ONLY_LIBRARY
906   encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
907   encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
908   encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
909#endif
910   /* now override with asm where appropriate */
911#ifndef FLAC__INTEGER_ONLY_LIBRARY
912# ifndef FLAC__NO_ASM
913   if(encoder->private_->cpuinfo.use_asm) {
914#  ifdef FLAC__CPU_IA32
915      FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
916#   ifdef FLAC__HAS_NASM
917      if(encoder->private_->cpuinfo.data.ia32.sse) {
918         if(encoder->protected_->max_lpc_order < 4)
919            encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
920         else if(encoder->protected_->max_lpc_order < 8)
921            encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
922         else if(encoder->protected_->max_lpc_order < 12)
923            encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
924         else
925            encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
926      }
927      else if(encoder->private_->cpuinfo.data.ia32._3dnow)
928         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
929      else
930         encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
931      if(encoder->private_->cpuinfo.data.ia32.mmx) {
932         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
933         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
934      }
935      else {
936         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
937         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
938      }
939      if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
940         encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
941#   endif /* FLAC__HAS_NASM */
942#  endif /* FLAC__CPU_IA32 */
943   }
944# endif /* !FLAC__NO_ASM */
945#endif /* !FLAC__INTEGER_ONLY_LIBRARY */
946   /* finally override based on wide-ness if necessary */
947   if(encoder->private_->use_wide_by_block) {
948      encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
949   }
950
951   /* set state to OK; from here on, errors are fatal and we'll override the state then */
952   encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
953
954#if FLAC__HAS_OGG
955   encoder->private_->is_ogg = is_ogg;
956   if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
957      encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
958      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
959   }
960#endif
961
962   encoder->private_->read_callback = read_callback;
963   encoder->private_->write_callback = write_callback;
964   encoder->private_->seek_callback = seek_callback;
965   encoder->private_->tell_callback = tell_callback;
966   encoder->private_->metadata_callback = metadata_callback;
967   encoder->private_->client_data = client_data;
968
969   if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
970      /* the above function sets the state for us in case of an error */
971      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
972   }
973
974   if(!FLAC__bitwriter_init(encoder->private_->frame)) {
975      encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
976      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
977   }
978
979   /*
980    * Set up the verify stuff if necessary
981    */
982   if(encoder->protected_->verify) {
983      /*
984       * First, set up the fifo which will hold the
985       * original signal to compare against
986       */
987      encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
988      for(i = 0; i < encoder->protected_->channels; i++) {
989         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))) {
990            encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
991            return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
992         }
993      }
994      encoder->private_->verify.input_fifo.tail = 0;
995
996      /*
997       * Now set up a stream decoder for verification
998       */
999      encoder->private_->verify.decoder = FLAC__stream_decoder_new();
1000      if(0 == encoder->private_->verify.decoder) {
1001         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1002         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1003      }
1004
1005      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) {
1006         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
1007         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1008      }
1009   }
1010   encoder->private_->verify.error_stats.absolute_sample = 0;
1011   encoder->private_->verify.error_stats.frame_number = 0;
1012   encoder->private_->verify.error_stats.channel = 0;
1013   encoder->private_->verify.error_stats.sample = 0;
1014   encoder->private_->verify.error_stats.expected = 0;
1015   encoder->private_->verify.error_stats.got = 0;
1016
1017   /*
1018    * These must be done before we write any metadata, because that
1019    * calls the write_callback, which uses these values.
1020    */
1021   encoder->private_->first_seekpoint_to_check = 0;
1022   encoder->private_->samples_written = 0;
1023   encoder->protected_->streaminfo_offset = 0;
1024   encoder->protected_->seektable_offset = 0;
1025   encoder->protected_->audio_offset = 0;
1026
1027   /*
1028    * write the stream header
1029    */
1030   if(encoder->protected_->verify)
1031      encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
1032   if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
1033      encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1034      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1035   }
1036   if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1037      /* the above function sets the state for us in case of an error */
1038      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1039   }
1040
1041   /*
1042    * write the STREAMINFO metadata block
1043    */
1044   if(encoder->protected_->verify)
1045      encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
1046   encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
1047   encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
1048   encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
1049   encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
1050   encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
1051   encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
1052   encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
1053   encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
1054   encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
1055   encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
1056   encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
1057   memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
1058   if(encoder->protected_->do_md5)
1059      FLAC__MD5Init(&encoder->private_->md5context);
1060   if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
1061      encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1062      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1063   }
1064   if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1065      /* the above function sets the state for us in case of an error */
1066      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1067   }
1068
1069   /*
1070    * Now that the STREAMINFO block is written, we can init this to an
1071    * absurdly-high value...
1072    */
1073   encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
1074   /* ... and clear this to 0 */
1075   encoder->private_->streaminfo.data.stream_info.total_samples = 0;
1076
1077   /*
1078    * Check to see if the supplied metadata contains a VORBIS_COMMENT;
1079    * if not, we will write an empty one (FLAC__add_metadata_block()
1080    * automatically supplies the vendor string).
1081    *
1082    * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
1083    * the STREAMINFO.  (In the case that metadata_has_vorbis_comment is
1084    * true it will have already insured that the metadata list is properly
1085    * ordered.)
1086    */
1087   if(!metadata_has_vorbis_comment) {
1088      FLAC__StreamMetadata vorbis_comment;
1089      vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1090      vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
1091      vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
1092      vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
1093      vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
1094      vorbis_comment.data.vorbis_comment.num_comments = 0;
1095      vorbis_comment.data.vorbis_comment.comments = 0;
1096      if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
1097         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1098         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1099      }
1100      if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1101         /* the above function sets the state for us in case of an error */
1102         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1103      }
1104   }
1105
1106   /*
1107    * write the user's metadata blocks
1108    */
1109   for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
1110      encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
1111      if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
1112         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
1113         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1114      }
1115      if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
1116         /* the above function sets the state for us in case of an error */
1117         return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1118      }
1119   }
1120
1121   /* now that all the metadata is written, we save the stream offset */
1122   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 */
1123      encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
1124      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1125   }
1126
1127   if(encoder->protected_->verify)
1128      encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
1129
1130   return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
1131}
1132
1133FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
1134   FLAC__StreamEncoder *encoder,
1135   FLAC__StreamEncoderWriteCallback write_callback,
1136   FLAC__StreamEncoderSeekCallback seek_callback,
1137   FLAC__StreamEncoderTellCallback tell_callback,
1138   FLAC__StreamEncoderMetadataCallback metadata_callback,
1139   void *client_data
1140)
1141{
1142   return init_stream_internal_(
1143      encoder,
1144      /*read_callback=*/0,
1145      write_callback,
1146      seek_callback,
1147      tell_callback,
1148      metadata_callback,
1149      client_data,
1150      /*is_ogg=*/false
1151   );
1152}
1153
1154FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
1155   FLAC__StreamEncoder *encoder,
1156   FLAC__StreamEncoderReadCallback read_callback,
1157   FLAC__StreamEncoderWriteCallback write_callback,
1158   FLAC__StreamEncoderSeekCallback seek_callback,
1159   FLAC__StreamEncoderTellCallback tell_callback,
1160   FLAC__StreamEncoderMetadataCallback metadata_callback,
1161   void *client_data
1162)
1163{
1164   return init_stream_internal_(
1165      encoder,
1166      read_callback,
1167      write_callback,
1168      seek_callback,
1169      tell_callback,
1170      metadata_callback,
1171      client_data,
1172      /*is_ogg=*/true
1173   );
1174}
1175 
1176static FLAC__StreamEncoderInitStatus init_FILE_internal_(
1177   FLAC__StreamEncoder *encoder,
1178   FILE *file,
1179   FLAC__StreamEncoderProgressCallback progress_callback,
1180   void *client_data,
1181   FLAC__bool is_ogg
1182)
1183{
1184   FLAC__StreamEncoderInitStatus init_status;
1185
1186   FLAC__ASSERT(0 != encoder);
1187   FLAC__ASSERT(0 != file);
1188
1189   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1190      return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1191
1192   /* double protection */
1193   if(file == 0) {
1194      encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1195      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1196   }
1197
1198   /*
1199    * To make sure that our file does not go unclosed after an error, we
1200    * must assign the FILE pointer before any further error can occur in
1201    * this routine.
1202    */
1203   if(file == stdout)
1204      file = get_binary_stdout_(); /* just to be safe */
1205
1206   encoder->private_->file = file;
1207
1208   encoder->private_->progress_callback = progress_callback;
1209   encoder->private_->bytes_written = 0;
1210   encoder->private_->samples_written = 0;
1211   encoder->private_->frames_written = 0;
1212
1213   init_status = init_stream_internal_(
1214      encoder,
1215      encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_ : 0,
1216      file_write_callback_,
1217      encoder->private_->file == stdout? 0 : file_seek_callback_,
1218      encoder->private_->file == stdout? 0 : file_tell_callback_,
1219      /*metadata_callback=*/0,
1220      client_data,
1221      is_ogg
1222   );
1223   if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
1224      /* the above function sets the state for us in case of an error */
1225      return init_status;
1226   }
1227
1228   {
1229      unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1230
1231      FLAC__ASSERT(blocksize != 0);
1232      encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
1233   }
1234
1235   return init_status;
1236}
1237 
1238FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
1239   FLAC__StreamEncoder *encoder,
1240   FILE *file,
1241   FLAC__StreamEncoderProgressCallback progress_callback,
1242   void *client_data
1243)
1244{
1245   return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
1246}
1247 
1248FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
1249   FLAC__StreamEncoder *encoder,
1250   FILE *file,
1251   FLAC__StreamEncoderProgressCallback progress_callback,
1252   void *client_data
1253)
1254{
1255   return init_FILE_internal_(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
1256}
1257
1258static FLAC__StreamEncoderInitStatus init_file_internal_(
1259   FLAC__StreamEncoder *encoder,
1260   const char *filename,
1261   FLAC__StreamEncoderProgressCallback progress_callback,
1262   void *client_data,
1263   FLAC__bool is_ogg
1264)
1265{
1266   FILE *file;
1267
1268   FLAC__ASSERT(0 != encoder);
1269
1270   /*
1271    * To make sure that our file does not go unclosed after an error, we
1272    * have to do the same entrance checks here that are later performed
1273    * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
1274    */
1275   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1276      return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
1277
1278   file = filename? fopen(filename, "w+b") : stdout;
1279
1280   if(file == 0) {
1281      encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
1282      return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
1283   }
1284
1285   return init_FILE_internal_(encoder, file, progress_callback, client_data, is_ogg);
1286}
1287
1288FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
1289   FLAC__StreamEncoder *encoder,
1290   const char *filename,
1291   FLAC__StreamEncoderProgressCallback progress_callback,
1292   void *client_data
1293)
1294{
1295   return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
1296}
1297
1298FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
1299   FLAC__StreamEncoder *encoder,
1300   const char *filename,
1301   FLAC__StreamEncoderProgressCallback progress_callback,
1302   void *client_data
1303)
1304{
1305   return init_file_internal_(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
1306}
1307
1308FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
1309{
1310   FLAC__bool error = false;
1311
1312   FLAC__ASSERT(0 != encoder);
1313   FLAC__ASSERT(0 != encoder->private_);
1314   FLAC__ASSERT(0 != encoder->protected_);
1315
1316   if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
1317      return true;
1318
1319   if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
1320      if(encoder->private_->current_sample_number != 0) {
1321         const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
1322         encoder->protected_->blocksize = encoder->private_->current_sample_number;
1323         if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
1324            error = true;
1325      }
1326   }
1327
1328   if(encoder->protected_->do_md5)
1329      FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
1330
1331   if(!encoder->private_->is_being_deleted) {
1332      if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
1333         if(encoder->private_->seek_callback) {
1334#if FLAC__HAS_OGG
1335            if(encoder->private_->is_ogg)
1336               update_ogg_metadata_(encoder);
1337            else
1338#endif
1339            update_metadata_(encoder);
1340
1341            /* check if an error occurred while updating metadata */
1342            if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
1343               error = true;
1344         }
1345         if(encoder->private_->metadata_callback)
1346            encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
1347      }
1348
1349      if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
1350         if(!error)
1351            encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
1352         error = true;
1353      }
1354   }
1355
1356   if(0 != encoder->private_->file) {
1357      if(encoder->private_->file != stdout)
1358         fclose(encoder->private_->file);
1359      encoder->private_->file = 0;
1360   }
1361
1362#if FLAC__HAS_OGG
1363   if(encoder->private_->is_ogg)
1364      FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
1365#endif
1366
1367   free_(encoder);
1368   set_defaults_(encoder);
1369
1370   if(!error)
1371      encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
1372
1373   return !error;
1374}
1375
1376FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
1377{
1378   FLAC__ASSERT(0 != encoder);
1379   FLAC__ASSERT(0 != encoder->private_);
1380   FLAC__ASSERT(0 != encoder->protected_);
1381   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1382      return false;
1383#if FLAC__HAS_OGG
1384   /* can't check encoder->private_->is_ogg since that's not set until init time */
1385   FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
1386   return true;
1387#else
1388   (void)value;
1389   return false;
1390#endif
1391}
1392
1393FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
1394{
1395   FLAC__ASSERT(0 != encoder);
1396   FLAC__ASSERT(0 != encoder->private_);
1397   FLAC__ASSERT(0 != encoder->protected_);
1398   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1399      return false;
1400#ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
1401   encoder->protected_->verify = value;
1402#endif
1403   return true;
1404}
1405
1406FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
1407{
1408   FLAC__ASSERT(0 != encoder);
1409   FLAC__ASSERT(0 != encoder->private_);
1410   FLAC__ASSERT(0 != encoder->protected_);
1411   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1412      return false;
1413   encoder->protected_->streamable_subset = value;
1414   return true;
1415}
1416
1417FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
1418{
1419   FLAC__ASSERT(0 != encoder);
1420   FLAC__ASSERT(0 != encoder->private_);
1421   FLAC__ASSERT(0 != encoder->protected_);
1422   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1423      return false;
1424   encoder->protected_->do_md5 = value;
1425   return true;
1426}
1427
1428FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
1429{
1430   FLAC__ASSERT(0 != encoder);
1431   FLAC__ASSERT(0 != encoder->private_);
1432   FLAC__ASSERT(0 != encoder->protected_);
1433   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1434      return false;
1435   encoder->protected_->channels = value;
1436   return true;
1437}
1438
1439FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
1440{
1441   FLAC__ASSERT(0 != encoder);
1442   FLAC__ASSERT(0 != encoder->private_);
1443   FLAC__ASSERT(0 != encoder->protected_);
1444   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1445      return false;
1446   encoder->protected_->bits_per_sample = value;
1447   return true;
1448}
1449
1450FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
1451{
1452   FLAC__ASSERT(0 != encoder);
1453   FLAC__ASSERT(0 != encoder->private_);
1454   FLAC__ASSERT(0 != encoder->protected_);
1455   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1456      return false;
1457   encoder->protected_->sample_rate = value;
1458   return true;
1459}
1460
1461FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
1462{
1463   FLAC__bool ok = true;
1464   FLAC__ASSERT(0 != encoder);
1465   FLAC__ASSERT(0 != encoder->private_);
1466   FLAC__ASSERT(0 != encoder->protected_);
1467   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1468      return false;
1469   if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
1470      value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
1471   ok &= FLAC__stream_encoder_set_do_mid_side_stereo          (encoder, compression_levels_[value].do_mid_side_stereo);
1472   ok &= FLAC__stream_encoder_set_loose_mid_side_stereo       (encoder, compression_levels_[value].loose_mid_side_stereo);
1473#ifndef FLAC__INTEGER_ONLY_LIBRARY
1474#if 0
1475   /* was: */
1476   ok &= FLAC__stream_encoder_set_apodization                 (encoder, compression_levels_[value].apodization);
1477   /* but it's too hard to specify the string in a locale-specific way */
1478#else
1479   encoder->protected_->num_apodizations = 1;
1480   encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1481   encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1482#endif
1483#endif
1484   ok &= FLAC__stream_encoder_set_max_lpc_order               (encoder, compression_levels_[value].max_lpc_order);
1485   ok &= FLAC__stream_encoder_set_qlp_coeff_precision         (encoder, compression_levels_[value].qlp_coeff_precision);
1486   ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search    (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
1487   ok &= FLAC__stream_encoder_set_do_escape_coding            (encoder, compression_levels_[value].do_escape_coding);
1488   ok &= FLAC__stream_encoder_set_do_exhaustive_model_search  (encoder, compression_levels_[value].do_exhaustive_model_search);
1489   ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
1490   ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
1491   ok &= FLAC__stream_encoder_set_rice_parameter_search_dist  (encoder, compression_levels_[value].rice_parameter_search_dist);
1492   return ok;
1493}
1494
1495FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
1496{
1497   FLAC__ASSERT(0 != encoder);
1498   FLAC__ASSERT(0 != encoder->private_);
1499   FLAC__ASSERT(0 != encoder->protected_);
1500   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1501      return false;
1502   encoder->protected_->blocksize = value;
1503   return true;
1504}
1505
1506FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1507{
1508   FLAC__ASSERT(0 != encoder);
1509   FLAC__ASSERT(0 != encoder->private_);
1510   FLAC__ASSERT(0 != encoder->protected_);
1511   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1512      return false;
1513   encoder->protected_->do_mid_side_stereo = value;
1514   return true;
1515}
1516
1517FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
1518{
1519   FLAC__ASSERT(0 != encoder);
1520   FLAC__ASSERT(0 != encoder->private_);
1521   FLAC__ASSERT(0 != encoder->protected_);
1522   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1523      return false;
1524   encoder->protected_->loose_mid_side_stereo = value;
1525   return true;
1526}
1527
1528/*@@@@add to tests*/
1529FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
1530{
1531   FLAC__ASSERT(0 != encoder);
1532   FLAC__ASSERT(0 != encoder->private_);
1533   FLAC__ASSERT(0 != encoder->protected_);
1534   FLAC__ASSERT(0 != specification);
1535   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1536      return false;
1537#ifdef FLAC__INTEGER_ONLY_LIBRARY
1538   (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
1539#else
1540   encoder->protected_->num_apodizations = 0;
1541   while(1) {
1542      const char *s = strchr(specification, ';');
1543      const size_t n = s? (size_t)(s - specification) : strlen(specification);
1544      if     (n==8  && 0 == strncmp("bartlett"     , specification, n))
1545         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
1546      else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
1547         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
1548      else if(n==8  && 0 == strncmp("blackman"     , specification, n))
1549         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
1550      else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
1551         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
1552      else if(n==6  && 0 == strncmp("connes"       , specification, n))
1553         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
1554      else if(n==7  && 0 == strncmp("flattop"      , specification, n))
1555         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
1556      else if(n>7   && 0 == strncmp("gauss("       , specification, 6)) {
1557         FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
1558         if (stddev > 0.0 && stddev <= 0.5) {
1559            encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
1560            encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
1561         }
1562      }
1563      else if(n==7  && 0 == strncmp("hamming"      , specification, n))
1564         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
1565      else if(n==4  && 0 == strncmp("hann"         , specification, n))
1566         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
1567      else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
1568         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
1569      else if(n==7  && 0 == strncmp("nuttall"      , specification, n))
1570         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
1571      else if(n==9  && 0 == strncmp("rectangle"    , specification, n))
1572         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
1573      else if(n==8  && 0 == strncmp("triangle"     , specification, n))
1574         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
1575      else if(n>7   && 0 == strncmp("tukey("       , specification, 6)) {
1576         FLAC__real p = (FLAC__real)strtod(specification+6, 0);
1577         if (p >= 0.0 && p <= 1.0) {
1578            encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
1579            encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
1580         }
1581      }
1582      else if(n==5  && 0 == strncmp("welch"        , specification, n))
1583         encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
1584      if (encoder->protected_->num_apodizations == 32)
1585         break;
1586      if (s)
1587         specification = s+1;
1588      else
1589         break;
1590   }
1591   if(encoder->protected_->num_apodizations == 0) {
1592      encoder->protected_->num_apodizations = 1;
1593      encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
1594      encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
1595   }
1596#endif
1597   return true;
1598}
1599
1600FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
1601{
1602   FLAC__ASSERT(0 != encoder);
1603   FLAC__ASSERT(0 != encoder->private_);
1604   FLAC__ASSERT(0 != encoder->protected_);
1605   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1606      return false;
1607   encoder->protected_->max_lpc_order = value;
1608   return true;
1609}
1610
1611FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
1612{
1613   FLAC__ASSERT(0 != encoder);
1614   FLAC__ASSERT(0 != encoder->private_);
1615   FLAC__ASSERT(0 != encoder->protected_);
1616   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1617      return false;
1618   encoder->protected_->qlp_coeff_precision = value;
1619   return true;
1620}
1621
1622FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1623{
1624   FLAC__ASSERT(0 != encoder);
1625   FLAC__ASSERT(0 != encoder->private_);
1626   FLAC__ASSERT(0 != encoder->protected_);
1627   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1628      return false;
1629   encoder->protected_->do_qlp_coeff_prec_search = value;
1630   return true;
1631}
1632
1633FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
1634{
1635   FLAC__ASSERT(0 != encoder);
1636   FLAC__ASSERT(0 != encoder->private_);
1637   FLAC__ASSERT(0 != encoder->protected_);
1638   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1639      return false;
1640#if 0
1641   /*@@@ deprecated: */
1642   encoder->protected_->do_escape_coding = value;
1643#else
1644   (void)value;
1645#endif
1646   return true;
1647}
1648
1649FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
1650{
1651   FLAC__ASSERT(0 != encoder);
1652   FLAC__ASSERT(0 != encoder->private_);
1653   FLAC__ASSERT(0 != encoder->protected_);
1654   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1655      return false;
1656   encoder->protected_->do_exhaustive_model_search = value;
1657   return true;
1658}
1659
1660FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1661{
1662   FLAC__ASSERT(0 != encoder);
1663   FLAC__ASSERT(0 != encoder->private_);
1664   FLAC__ASSERT(0 != encoder->protected_);
1665   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1666      return false;
1667   encoder->protected_->min_residual_partition_order = value;
1668   return true;
1669}
1670
1671FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
1672{
1673   FLAC__ASSERT(0 != encoder);
1674   FLAC__ASSERT(0 != encoder->private_);
1675   FLAC__ASSERT(0 != encoder->protected_);
1676   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1677      return false;
1678   encoder->protected_->max_residual_partition_order = value;
1679   return true;
1680}
1681
1682FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
1683{
1684   FLAC__ASSERT(0 != encoder);
1685   FLAC__ASSERT(0 != encoder->private_);
1686   FLAC__ASSERT(0 != encoder->protected_);
1687   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1688      return false;
1689#if 0
1690   /*@@@ deprecated: */
1691   encoder->protected_->rice_parameter_search_dist = value;
1692#else
1693   (void)value;
1694#endif
1695   return true;
1696}
1697
1698FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
1699{
1700   FLAC__ASSERT(0 != encoder);
1701   FLAC__ASSERT(0 != encoder->private_);
1702   FLAC__ASSERT(0 != encoder->protected_);
1703   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1704      return false;
1705   encoder->protected_->total_samples_estimate = value;
1706   return true;
1707}
1708
1709FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
1710{
1711   FLAC__ASSERT(0 != encoder);
1712   FLAC__ASSERT(0 != encoder->private_);
1713   FLAC__ASSERT(0 != encoder->protected_);
1714   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1715      return false;
1716   if(0 == metadata)
1717      num_blocks = 0;
1718   if(0 == num_blocks)
1719      metadata = 0;
1720   /* realloc() does not do exactly what we want so... */
1721   if(encoder->protected_->metadata) {
1722      free(encoder->protected_->metadata);
1723      encoder->protected_->metadata = 0;
1724      encoder->protected_->num_metadata_blocks = 0;
1725   }
1726   if(num_blocks) {
1727      FLAC__StreamMetadata **m;
1728      if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
1729         return false;
1730      memcpy(m, metadata, sizeof(m[0]) * num_blocks);
1731      encoder->protected_->metadata = m;
1732      encoder->protected_->num_metadata_blocks = num_blocks;
1733   }
1734#if FLAC__HAS_OGG
1735   if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
1736      return false;
1737#endif
1738   return true;
1739}
1740
1741/*
1742 * These three functions are not static, but not publically exposed in
1743 * include/FLAC/ either.  They are used by the test suite.
1744 */
1745FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1746{
1747   FLAC__ASSERT(0 != encoder);
1748   FLAC__ASSERT(0 != encoder->private_);
1749   FLAC__ASSERT(0 != encoder->protected_);
1750   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1751      return false;
1752   encoder->private_->disable_constant_subframes = value;
1753   return true;
1754}
1755
1756FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1757{
1758   FLAC__ASSERT(0 != encoder);
1759   FLAC__ASSERT(0 != encoder->private_);
1760   FLAC__ASSERT(0 != encoder->protected_);
1761   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1762      return false;
1763   encoder->private_->disable_fixed_subframes = value;
1764   return true;
1765}
1766
1767FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
1768{
1769   FLAC__ASSERT(0 != encoder);
1770   FLAC__ASSERT(0 != encoder->private_);
1771   FLAC__ASSERT(0 != encoder->protected_);
1772   if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
1773      return false;
1774   encoder->private_->disable_verbatim_subframes = value;
1775   return true;
1776}
1777
1778FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
1779{
1780   FLAC__ASSERT(0 != encoder);
1781   FLAC__ASSERT(0 != encoder->private_);
1782   FLAC__ASSERT(0 != encoder->protected_);
1783   return encoder->protected_->state;
1784}
1785
1786FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
1787{
1788   FLAC__ASSERT(0 != encoder);
1789   FLAC__ASSERT(0 != encoder->private_);
1790   FLAC__ASSERT(0 != encoder->protected_);
1791   if(encoder->protected_->verify)
1792      return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
1793   else
1794      return FLAC__STREAM_DECODER_UNINITIALIZED;
1795}
1796
1797FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
1798{
1799   FLAC__ASSERT(0 != encoder);
1800   FLAC__ASSERT(0 != encoder->private_);
1801   FLAC__ASSERT(0 != encoder->protected_);
1802   if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
1803      return FLAC__StreamEncoderStateString[encoder->protected_->state];
1804   else
1805      return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
1806}
1807
1808FLAC_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)
1809{
1810   FLAC__ASSERT(0 != encoder);
1811   FLAC__ASSERT(0 != encoder->private_);
1812   FLAC__ASSERT(0 != encoder->protected_);
1813   if(0 != absolute_sample)
1814      *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
1815   if(0 != frame_number)
1816      *frame_number = encoder->private_->verify.error_stats.frame_number;
1817   if(0 != channel)
1818      *channel = encoder->private_->verify.error_stats.channel;
1819   if(0 != sample)
1820      *sample = encoder->private_->verify.error_stats.sample;
1821   if(0 != expected)
1822      *expected = encoder->private_->verify.error_stats.expected;
1823   if(0 != got)
1824      *got = encoder->private_->verify.error_stats.got;
1825}
1826
1827FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
1828{
1829   FLAC__ASSERT(0 != encoder);
1830   FLAC__ASSERT(0 != encoder->private_);
1831   FLAC__ASSERT(0 != encoder->protected_);
1832   return encoder->protected_->verify;
1833}
1834
1835FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
1836{
1837   FLAC__ASSERT(0 != encoder);
1838   FLAC__ASSERT(0 != encoder->private_);
1839   FLAC__ASSERT(0 != encoder->protected_);
1840   return encoder->protected_->streamable_subset;
1841}
1842
1843FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
1844{
1845   FLAC__ASSERT(0 != encoder);
1846   FLAC__ASSERT(0 != encoder->private_);
1847   FLAC__ASSERT(0 != encoder->protected_);
1848   return encoder->protected_->do_md5;
1849}
1850
1851FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
1852{
1853   FLAC__ASSERT(0 != encoder);
1854   FLAC__ASSERT(0 != encoder->private_);
1855   FLAC__ASSERT(0 != encoder->protected_);
1856   return encoder->protected_->channels;
1857}
1858
1859FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
1860{
1861   FLAC__ASSERT(0 != encoder);
1862   FLAC__ASSERT(0 != encoder->private_);
1863   FLAC__ASSERT(0 != encoder->protected_);
1864   return encoder->protected_->bits_per_sample;
1865}
1866
1867FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
1868{
1869   FLAC__ASSERT(0 != encoder);
1870   FLAC__ASSERT(0 != encoder->private_);
1871   FLAC__ASSERT(0 != encoder->protected_);
1872   return encoder->protected_->sample_rate;
1873}
1874
1875FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
1876{
1877   FLAC__ASSERT(0 != encoder);
1878   FLAC__ASSERT(0 != encoder->private_);
1879   FLAC__ASSERT(0 != encoder->protected_);
1880   return encoder->protected_->blocksize;
1881}
1882
1883FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1884{
1885   FLAC__ASSERT(0 != encoder);
1886   FLAC__ASSERT(0 != encoder->private_);
1887   FLAC__ASSERT(0 != encoder->protected_);
1888   return encoder->protected_->do_mid_side_stereo;
1889}
1890
1891FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
1892{
1893   FLAC__ASSERT(0 != encoder);
1894   FLAC__ASSERT(0 != encoder->private_);
1895   FLAC__ASSERT(0 != encoder->protected_);
1896   return encoder->protected_->loose_mid_side_stereo;
1897}
1898
1899FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
1900{
1901   FLAC__ASSERT(0 != encoder);
1902   FLAC__ASSERT(0 != encoder->private_);
1903   FLAC__ASSERT(0 != encoder->protected_);
1904   return encoder->protected_->max_lpc_order;
1905}
1906
1907FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
1908{
1909   FLAC__ASSERT(0 != encoder);
1910   FLAC__ASSERT(0 != encoder->private_);
1911   FLAC__ASSERT(0 != encoder->protected_);
1912   return encoder->protected_->qlp_coeff_precision;
1913}
1914
1915FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
1916{
1917   FLAC__ASSERT(0 != encoder);
1918   FLAC__ASSERT(0 != encoder->private_);
1919   FLAC__ASSERT(0 != encoder->protected_);
1920   return encoder->protected_->do_qlp_coeff_prec_search;
1921}
1922
1923FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
1924{
1925   FLAC__ASSERT(0 != encoder);
1926   FLAC__ASSERT(0 != encoder->private_);
1927   FLAC__ASSERT(0 != encoder->protected_);
1928   return encoder->protected_->do_escape_coding;
1929}
1930
1931FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
1932{
1933   FLAC__ASSERT(0 != encoder);
1934   FLAC__ASSERT(0 != encoder->private_);
1935   FLAC__ASSERT(0 != encoder->protected_);
1936   return encoder->protected_->do_exhaustive_model_search;
1937}
1938
1939FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
1940{
1941   FLAC__ASSERT(0 != encoder);
1942   FLAC__ASSERT(0 != encoder->private_);
1943   FLAC__ASSERT(0 != encoder->protected_);
1944   return encoder->protected_->min_residual_partition_order;
1945}
1946
1947FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
1948{
1949   FLAC__ASSERT(0 != encoder);
1950   FLAC__ASSERT(0 != encoder->private_);
1951   FLAC__ASSERT(0 != encoder->protected_);
1952   return encoder->protected_->max_residual_partition_order;
1953}
1954
1955FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
1956{
1957   FLAC__ASSERT(0 != encoder);
1958   FLAC__ASSERT(0 != encoder->private_);
1959   FLAC__ASSERT(0 != encoder->protected_);
1960   return encoder->protected_->rice_parameter_search_dist;
1961}
1962
1963FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
1964{
1965   FLAC__ASSERT(0 != encoder);
1966   FLAC__ASSERT(0 != encoder->private_);
1967   FLAC__ASSERT(0 != encoder->protected_);
1968   return encoder->protected_->total_samples_estimate;
1969}
1970
1971FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
1972{
1973   unsigned i, j = 0, channel;
1974   const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
1975
1976   FLAC__ASSERT(0 != encoder);
1977   FLAC__ASSERT(0 != encoder->private_);
1978   FLAC__ASSERT(0 != encoder->protected_);
1979   FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
1980
1981   do {
1982      const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
1983
1984      if(encoder->protected_->verify)
1985         append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
1986
1987      for(channel = 0; channel < channels; channel++)
1988         memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
1989
1990      if(encoder->protected_->do_mid_side_stereo) {
1991         FLAC__ASSERT(channels == 2);
1992         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
1993         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
1994            encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
1995            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' ! */
1996         }
1997      }
1998      else
1999         j += n;
2000
2001      encoder->private_->current_sample_number += n;
2002
2003      /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2004      if(encoder->private_->current_sample_number > blocksize) {
2005         FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
2006         FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2007         if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2008            return false;
2009         /* move unprocessed overread samples to beginnings of arrays */
2010         for(channel = 0; channel < channels; channel++)
2011            encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2012         if(encoder->protected_->do_mid_side_stereo) {
2013            encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2014            encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2015         }
2016         encoder->private_->current_sample_number = 1;
2017      }
2018   } while(j < samples);
2019
2020   return true;
2021}
2022
2023FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
2024{
2025   unsigned i, j, k, channel;
2026   FLAC__int32 x, mid, side;
2027   const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
2028
2029   FLAC__ASSERT(0 != encoder);
2030   FLAC__ASSERT(0 != encoder->private_);
2031   FLAC__ASSERT(0 != encoder->protected_);
2032   FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2033
2034   j = k = 0;
2035   /*
2036    * we have several flavors of the same basic loop, optimized for
2037    * different conditions:
2038    */
2039   if(encoder->protected_->do_mid_side_stereo && channels == 2) {
2040      /*
2041       * stereo coding: unroll channel loop
2042       */
2043      do {
2044         if(encoder->protected_->verify)
2045            append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2046
2047         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2048         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2049            encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
2050            x = buffer[k++];
2051            encoder->private_->integer_signal[1][i] = x;
2052            mid += x;
2053            side -= x;
2054            mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
2055            encoder->private_->integer_signal_mid_side[1][i] = side;
2056            encoder->private_->integer_signal_mid_side[0][i] = mid;
2057         }
2058         encoder->private_->current_sample_number = i;
2059         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2060         if(i > blocksize) {
2061            if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2062               return false;
2063            /* move unprocessed overread samples to beginnings of arrays */
2064            FLAC__ASSERT(i == blocksize+OVERREAD_);
2065            FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2066            encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
2067            encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
2068            encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
2069            encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
2070            encoder->private_->current_sample_number = 1;
2071         }
2072      } while(j < samples);
2073   }
2074   else {
2075      /*
2076       * independent channel coding: buffer each channel in inner loop
2077       */
2078      do {
2079         if(encoder->protected_->verify)
2080            append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
2081
2082         /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
2083         for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
2084            for(channel = 0; channel < channels; channel++)
2085               encoder->private_->integer_signal[channel][i] = buffer[k++];
2086         }
2087         encoder->private_->current_sample_number = i;
2088         /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
2089         if(i > blocksize) {
2090            if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
2091               return false;
2092            /* move unprocessed overread samples to beginnings of arrays */
2093            FLAC__ASSERT(i == blocksize+OVERREAD_);
2094            FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
2095            for(channel = 0; channel < channels; channel++)
2096               encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
2097            encoder->private_->current_sample_number = 1;
2098         }
2099      } while(j < samples);
2100   }
2101
2102   return true;
2103}
2104
2105/***********************************************************************
2106 *
2107 * Private class methods
2108 *
2109 ***********************************************************************/
2110
2111void set_defaults_(FLAC__StreamEncoder *encoder)
2112{
2113   FLAC__ASSERT(0 != encoder);
2114
2115#ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
2116   encoder->protected_->verify = true;
2117#else
2118   encoder->protected_->verify = false;
2119#endif
2120   encoder->protected_->streamable_subset = true;
2121   encoder->protected_->do_md5 = true;
2122   encoder->protected_->do_mid_side_stereo = false;
2123   encoder->protected_->loose_mid_side_stereo = false;
2124   encoder->protected_->channels = 2;
2125   encoder->protected_->bits_per_sample = 16;
2126   encoder->protected_->sample_rate = 44100;
2127   encoder->protected_->blocksize = 0;
2128#ifndef FLAC__INTEGER_ONLY_LIBRARY
2129   encoder->protected_->num_apodizations = 1;
2130   encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
2131   encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
2132#endif
2133   encoder->protected_->max_lpc_order = 0;
2134   encoder->protected_->qlp_coeff_precision = 0;
2135   encoder->protected_->do_qlp_coeff_prec_search = false;
2136   encoder->protected_->do_exhaustive_model_search = false;
2137   encoder->protected_->do_escape_coding = false;
2138   encoder->protected_->min_residual_partition_order = 0;
2139   encoder->protected_->max_residual_partition_order = 0;
2140   encoder->protected_->rice_parameter_search_dist = 0;
2141   encoder->protected_->total_samples_estimate = 0;
2142   encoder->protected_->metadata = 0;
2143   encoder->protected_->num_metadata_blocks = 0;
2144
2145   encoder->private_->seek_table = 0;
2146   encoder->private_->disable_constant_subframes = false;
2147   encoder->private_->disable_fixed_subframes = false;
2148   encoder->private_->disable_verbatim_subframes = false;
2149#if FLAC__HAS_OGG
2150   encoder->private_->is_ogg = false;
2151#endif
2152   encoder->private_->read_callback = 0;
2153   encoder->private_->write_callback = 0;
2154   encoder->private_->seek_callback = 0;
2155   encoder->private_->tell_callback = 0;
2156   encoder->private_->metadata_callback = 0;
2157   encoder->private_->progress_callback = 0;
2158   encoder->private_->client_data = 0;
2159
2160#if FLAC__HAS_OGG
2161   FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
2162#endif
2163}
2164
2165void free_(FLAC__StreamEncoder *encoder)
2166{
2167   unsigned i, channel;
2168
2169   FLAC__ASSERT(0 != encoder);
2170   if(encoder->protected_->metadata) {
2171      free(encoder->protected_->metadata);
2172      encoder->protected_->metadata = 0;
2173      encoder->protected_->num_metadata_blocks = 0;
2174   }
2175   for(i = 0; i < encoder->protected_->channels; i++) {
2176      if(0 != encoder->private_->integer_signal_unaligned[i]) {
2177         free(encoder->private_->integer_signal_unaligned[i]);
2178         encoder->private_->integer_signal_unaligned[i] = 0;
2179      }
2180#ifndef FLAC__INTEGER_ONLY_LIBRARY
2181      if(0 != encoder->private_->real_signal_unaligned[i]) {
2182         free(encoder->private_->real_signal_unaligned[i]);
2183         encoder->private_->real_signal_unaligned[i] = 0;
2184      }
2185#endif
2186   }
2187   for(i = 0; i < 2; i++) {
2188      if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
2189         free(encoder->private_->integer_signal_mid_side_unaligned[i]);
2190         encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
2191      }
2192#ifndef FLAC__INTEGER_ONLY_LIBRARY
2193      if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
2194         free(encoder->private_->real_signal_mid_side_unaligned[i]);
2195         encoder->private_->real_signal_mid_side_unaligned[i] = 0;
2196      }
2197#endif
2198   }
2199#ifndef FLAC__INTEGER_ONLY_LIBRARY
2200   for(i = 0; i < encoder->protected_->num_apodizations; i++) {
2201      if(0 != encoder->private_->window_unaligned[i]) {
2202         free(encoder->private_->window_unaligned[i]);
2203         encoder->private_->window_unaligned[i] = 0;
2204      }
2205   }
2206   if(0 != encoder->private_->windowed_signal_unaligned) {
2207      free(encoder->private_->windowed_signal_unaligned);
2208      encoder->private_->windowed_signal_unaligned = 0;
2209   }
2210#endif
2211   for(channel = 0; channel < encoder->protected_->channels; channel++) {
2212      for(i = 0; i < 2; i++) {
2213         if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
2214            free(encoder->private_->residual_workspace_unaligned[channel][i]);
2215            encoder->private_->residual_workspace_unaligned[channel][i] = 0;
2216         }
2217      }
2218   }
2219   for(channel = 0; channel < 2; channel++) {
2220      for(i = 0; i < 2; i++) {
2221         if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
2222            free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
2223            encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
2224         }
2225      }
2226   }
2227   if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
2228      free(encoder->private_->abs_residual_partition_sums_unaligned);
2229      encoder->private_->abs_residual_partition_sums_unaligned = 0;
2230   }
2231   if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
2232      free(encoder->private_->raw_bits_per_partition_unaligned);
2233      encoder->private_->raw_bits_per_partition_unaligned = 0;
2234   }
2235   if(encoder->protected_->verify) {
2236      for(i = 0; i < encoder->protected_->channels; i++) {
2237         if(0 != encoder->private_->verify.input_fifo.data[i]) {
2238            free(encoder->private_->verify.input_fifo.data[i]);
2239            encoder->private_->verify.input_fifo.data[i] = 0;
2240         }
2241      }
2242   }
2243   FLAC__bitwriter_free(encoder->private_->frame);
2244}
2245
2246FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
2247{
2248   FLAC__bool ok;
2249   unsigned i, channel;
2250
2251   FLAC__ASSERT(new_blocksize > 0);
2252   FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2253   FLAC__ASSERT(encoder->private_->current_sample_number == 0);
2254
2255   /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
2256   if(new_blocksize <= encoder->private_->input_capacity)
2257      return true;
2258
2259   ok = true;
2260
2261   /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
2262    * requires that the input arrays (in our case the integer signals)
2263    * have a buffer of up to 3 zeroes in front (at negative indices) for
2264    * alignment purposes; we use 4 in front to keep the data well-aligned.
2265    */
2266
2267   for(i = 0; ok && i < encoder->protected_->channels; i++) {
2268      ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
2269      memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
2270      encoder->private_->integer_signal[i] += 4;
2271#ifndef FLAC__INTEGER_ONLY_LIBRARY
2272#if 0 /* @@@ currently unused */
2273      if(encoder->protected_->max_lpc_order > 0)
2274         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
2275#endif
2276#endif
2277   }
2278   for(i = 0; ok && i < 2; i++) {
2279      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]);
2280      memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
2281      encoder->private_->integer_signal_mid_side[i] += 4;
2282#ifndef FLAC__INTEGER_ONLY_LIBRARY
2283#if 0 /* @@@ currently unused */
2284      if(encoder->protected_->max_lpc_order > 0)
2285         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]);
2286#endif
2287#endif
2288   }
2289#ifndef FLAC__INTEGER_ONLY_LIBRARY
2290   if(ok && encoder->protected_->max_lpc_order > 0) {
2291      for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
2292         ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
2293      ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
2294   }
2295#endif
2296   for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
2297      for(i = 0; ok && i < 2; i++) {
2298         ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
2299      }
2300   }
2301   for(channel = 0; ok && channel < 2; channel++) {
2302      for(i = 0; ok && i < 2; i++) {
2303         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]);
2304      }
2305   }
2306   /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
2307   /*@@@ 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) */
2308   ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
2309   if(encoder->protected_->do_escape_coding)
2310      ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
2311
2312   /* now adjust the windows if the blocksize has changed */
2313#ifndef FLAC__INTEGER_ONLY_LIBRARY
2314   if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
2315      for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
2316         switch(encoder->protected_->apodizations[i].type) {
2317            case FLAC__APODIZATION_BARTLETT:
2318               FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
2319               break;
2320            case FLAC__APODIZATION_BARTLETT_HANN:
2321               FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
2322               break;
2323            case FLAC__APODIZATION_BLACKMAN:
2324               FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
2325               break;
2326            case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
2327               FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
2328               break;
2329            case FLAC__APODIZATION_CONNES:
2330               FLAC__window_connes(encoder->private_->window[i], new_blocksize);
2331               break;
2332            case FLAC__APODIZATION_FLATTOP:
2333               FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
2334               break;
2335            case FLAC__APODIZATION_GAUSS:
2336               FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
2337               break;
2338            case FLAC__APODIZATION_HAMMING:
2339               FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
2340               break;
2341            case FLAC__APODIZATION_HANN:
2342               FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2343               break;
2344            case FLAC__APODIZATION_KAISER_BESSEL:
2345               FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
2346               break;
2347            case FLAC__APODIZATION_NUTTALL:
2348               FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
2349               break;
2350            case FLAC__APODIZATION_RECTANGLE:
2351               FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
2352               break;
2353            case FLAC__APODIZATION_TRIANGLE:
2354               FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
2355               break;
2356            case FLAC__APODIZATION_TUKEY:
2357               FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
2358               break;
2359            case FLAC__APODIZATION_WELCH:
2360               FLAC__window_welch(encoder->private_->window[i], new_blocksize);
2361               break;
2362            default:
2363               FLAC__ASSERT(0);
2364               /* double protection */
2365               FLAC__window_hann(encoder->private_->window[i], new_blocksize);
2366               break;
2367         }
2368      }
2369   }
2370#endif
2371
2372   if(ok)
2373      encoder->private_->input_capacity = new_blocksize;
2374   else
2375      encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2376
2377   return ok;
2378}
2379
2380FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
2381{
2382   const FLAC__byte *buffer;
2383   size_t bytes;
2384
2385   FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2386
2387   if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
2388      encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2389      return false;
2390   }
2391
2392   if(encoder->protected_->verify) {
2393      encoder->private_->verify.output.data = buffer;
2394      encoder->private_->verify.output.bytes = bytes;
2395      if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
2396         encoder->private_->verify.needs_magic_hack = true;
2397      }
2398      else {
2399         if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
2400            FLAC__bitwriter_release_buffer(encoder->private_->frame);
2401            FLAC__bitwriter_clear(encoder->private_->frame);
2402            if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
2403               encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
2404            return false;
2405         }
2406      }
2407   }
2408
2409   if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2410      FLAC__bitwriter_release_buffer(encoder->private_->frame);
2411      FLAC__bitwriter_clear(encoder->private_->frame);
2412      encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2413      return false;
2414   }
2415
2416   FLAC__bitwriter_release_buffer(encoder->private_->frame);
2417   FLAC__bitwriter_clear(encoder->private_->frame);
2418
2419   if(samples > 0) {
2420      encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
2421      encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
2422   }
2423
2424   return true;
2425}
2426
2427FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
2428{
2429   FLAC__StreamEncoderWriteStatus status;
2430   FLAC__uint64 output_position = 0;
2431
2432   /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
2433   if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
2434      encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2435      return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
2436   }
2437
2438   /*
2439    * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
2440    */
2441   if(samples == 0) {
2442      FLAC__MetadataType type = (buffer[0] & 0x7f);
2443      if(type == FLAC__METADATA_TYPE_STREAMINFO)
2444         encoder->protected_->streaminfo_offset = output_position;
2445      else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
2446         encoder->protected_->seektable_offset = output_position;
2447   }
2448
2449   /*
2450    * Mark the current seek point if hit (if audio_offset == 0 that
2451    * means we're still writing metadata and haven't hit the first
2452    * frame yet)
2453    */
2454   if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
2455      const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
2456      const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
2457      const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
2458      FLAC__uint64 test_sample;
2459      unsigned i;
2460      for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
2461         test_sample = encoder->private_->seek_table->points[i].sample_number;
2462         if(test_sample > frame_last_sample) {
2463            break;
2464         }
2465         else if(test_sample >= frame_first_sample) {
2466            encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
2467            encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
2468            encoder->private_->seek_table->points[i].frame_samples = blocksize;
2469            encoder->private_->first_seekpoint_to_check++;
2470            /* DO NOT: "break;" and here's why:
2471             * The seektable template may contain more than one target
2472             * sample for any given frame; we will keep looping, generating
2473             * duplicate seekpoints for them, and we'll clean it up later,
2474             * just before writing the seektable back to the metadata.
2475             */
2476         }
2477         else {
2478            encoder->private_->first_seekpoint_to_check++;
2479         }
2480      }
2481   }
2482
2483#if FLAC__HAS_OGG
2484   if(encoder->private_->is_ogg) {
2485      status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
2486         &encoder->protected_->ogg_encoder_aspect,
2487         buffer,
2488         bytes,
2489         samples,
2490         encoder->private_->current_frame_number,
2491         is_last_block,
2492         (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
2493         encoder,
2494         encoder->private_->client_data
2495      );
2496   }
2497   else
2498#endif
2499   status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
2500
2501   if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2502      encoder->private_->bytes_written += bytes;
2503      encoder->private_->samples_written += samples;
2504      /* we keep a high watermark on the number of frames written because
2505       * when the encoder goes back to write metadata, 'current_frame'
2506       * will drop back to 0.
2507       */
2508      encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
2509   }
2510   else
2511      encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2512
2513   return status;
2514}
2515
2516/* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2517void update_metadata_(const FLAC__StreamEncoder *encoder)
2518{
2519   FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2520   const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2521   const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2522   const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2523   const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2524   const unsigned bps = metadata->data.stream_info.bits_per_sample;
2525   FLAC__StreamEncoderSeekStatus seek_status;
2526
2527   FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2528
2529   /* All this is based on intimate knowledge of the stream header
2530    * layout, but a change to the header format that would break this
2531    * would also break all streams encoded in the previous format.
2532    */
2533
2534   /*
2535    * Write MD5 signature
2536    */
2537   {
2538      const unsigned md5_offset =
2539         FLAC__STREAM_METADATA_HEADER_LENGTH +
2540         (
2541            FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2542            FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2543            FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2544            FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2545            FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2546            FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2547            FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2548            FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2549         ) / 8;
2550
2551      if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
2552         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2553            encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2554         return;
2555      }
2556      if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2557         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2558         return;
2559      }
2560   }
2561
2562   /*
2563    * Write total samples
2564    */
2565   {
2566      const unsigned total_samples_byte_offset =
2567         FLAC__STREAM_METADATA_HEADER_LENGTH +
2568         (
2569            FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2570            FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2571            FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2572            FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2573            FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2574            FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2575            FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2576            - 4
2577         ) / 8;
2578
2579      b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
2580      b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2581      b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2582      b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2583      b[4] = (FLAC__byte)(samples & 0xFF);
2584      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) {
2585         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2586            encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2587         return;
2588      }
2589      if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2590         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2591         return;
2592      }
2593   }
2594
2595   /*
2596    * Write min/max framesize
2597    */
2598   {
2599      const unsigned min_framesize_offset =
2600         FLAC__STREAM_METADATA_HEADER_LENGTH +
2601         (
2602            FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2603            FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2604         ) / 8;
2605
2606      b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2607      b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2608      b[2] = (FLAC__byte)(min_framesize & 0xFF);
2609      b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2610      b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2611      b[5] = (FLAC__byte)(max_framesize & 0xFF);
2612      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) {
2613         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2614            encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2615         return;
2616      }
2617      if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2618         encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2619         return;
2620      }
2621   }
2622
2623   /*
2624    * Write seektable
2625    */
2626   if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2627      unsigned i;
2628
2629      FLAC__format_seektable_sort(encoder->private_->seek_table);
2630
2631      FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2632
2633      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) {
2634         if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
2635            encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2636         return;
2637      }
2638
2639      for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
2640         FLAC__uint64 xx;
2641         unsigned x;
2642         xx = encoder->private_->seek_table->points[i].sample_number;
2643         b[7] = (FLAC__byte)xx; xx >>= 8;
2644         b[6] = (FLAC__byte)xx; xx >>= 8;
2645         b[5] = (FLAC__byte)xx; xx >>= 8;
2646         b[4] = (FLAC__byte)xx; xx >>= 8;
2647         b[3] = (FLAC__byte)xx; xx >>= 8;
2648         b[2] = (FLAC__byte)xx; xx >>= 8;
2649         b[1] = (FLAC__byte)xx; xx >>= 8;
2650         b[0] = (FLAC__byte)xx; xx >>= 8;
2651         xx = encoder->private_->seek_table->points[i].stream_offset;
2652         b[15] = (FLAC__byte)xx; xx >>= 8;
2653         b[14] = (FLAC__byte)xx; xx >>= 8;
2654         b[13] = (FLAC__byte)xx; xx >>= 8;
2655         b[12] = (FLAC__byte)xx; xx >>= 8;
2656         b[11] = (FLAC__byte)xx; xx >>= 8;
2657         b[10] = (FLAC__byte)xx; xx >>= 8;
2658         b[9] = (FLAC__byte)xx; xx >>= 8;
2659         b[8] = (FLAC__byte)xx; xx >>= 8;
2660         x = encoder->private_->seek_table->points[i].frame_samples;
2661         b[17] = (FLAC__byte)x; x >>= 8;
2662         b[16] = (FLAC__byte)x; x >>= 8;
2663         if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
2664            encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
2665            return;
2666         }
2667      }
2668   }
2669}
2670
2671#if FLAC__HAS_OGG
2672/* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks.  */
2673void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
2674{
2675   /* the # of bytes in the 1st packet that precede the STREAMINFO */
2676   static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
2677      FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
2678      FLAC__OGG_MAPPING_MAGIC_LENGTH +
2679      FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
2680      FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
2681      FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
2682      FLAC__STREAM_SYNC_LENGTH
2683   ;
2684   FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
2685   const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
2686   const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
2687   const unsigned min_framesize = metadata->data.stream_info.min_framesize;
2688   const unsigned max_framesize = metadata->data.stream_info.max_framesize;
2689   ogg_page page;
2690
2691   FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
2692   FLAC__ASSERT(0 != encoder->private_->seek_callback);
2693
2694   /* Pre-check that client supports seeking, since we don't want the
2695    * ogg_helper code to ever have to deal with this condition.
2696    */
2697   if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
2698      return;
2699
2700   /* All this is based on intimate knowledge of the stream header
2701    * layout, but a change to the header format that would break this
2702    * would also break all streams encoded in the previous format.
2703    */
2704
2705   /**
2706    ** Write STREAMINFO stats
2707    **/
2708   simple_ogg_page__init(&page);
2709   if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2710      simple_ogg_page__clear(&page);
2711      return; /* state already set */
2712   }
2713
2714   /*
2715    * Write MD5 signature
2716    */
2717   {
2718      const unsigned md5_offset =
2719         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2720         FLAC__STREAM_METADATA_HEADER_LENGTH +
2721         (
2722            FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2723            FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2724            FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2725            FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2726            FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2727            FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2728            FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
2729            FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
2730         ) / 8;
2731
2732      if(md5_offset + 16 > (unsigned)page.body_len) {
2733         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2734         simple_ogg_page__clear(&page);
2735         return;
2736      }
2737      memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
2738   }
2739
2740   /*
2741    * Write total samples
2742    */
2743   {
2744      const unsigned total_samples_byte_offset =
2745         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2746         FLAC__STREAM_METADATA_HEADER_LENGTH +
2747         (
2748            FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2749            FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
2750            FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
2751            FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
2752            FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
2753            FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
2754            FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
2755            - 4
2756         ) / 8;
2757
2758      if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
2759         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2760         simple_ogg_page__clear(&page);
2761         return;
2762      }
2763      b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
2764      b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
2765      b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
2766      b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
2767      b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
2768      b[4] = (FLAC__byte)(samples & 0xFF);
2769      memcpy(page.body + total_samples_byte_offset, b, 5);
2770   }
2771
2772   /*
2773    * Write min/max framesize
2774    */
2775   {
2776      const unsigned min_framesize_offset =
2777         FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
2778         FLAC__STREAM_METADATA_HEADER_LENGTH +
2779         (
2780            FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
2781            FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
2782         ) / 8;
2783
2784      if(min_framesize_offset + 6 > (unsigned)page.body_len) {
2785         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2786         simple_ogg_page__clear(&page);
2787         return;
2788      }
2789      b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
2790      b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
2791      b[2] = (FLAC__byte)(min_framesize & 0xFF);
2792      b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
2793      b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
2794      b[5] = (FLAC__byte)(max_framesize & 0xFF);
2795      memcpy(page.body + min_framesize_offset, b, 6);
2796   }
2797   if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2798      simple_ogg_page__clear(&page);
2799      return; /* state already set */
2800   }
2801   simple_ogg_page__clear(&page);
2802
2803   /*
2804    * Write seektable
2805    */
2806   if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
2807      unsigned i;
2808      FLAC__byte *p;
2809
2810      FLAC__format_seektable_sort(encoder->private_->seek_table);
2811
2812      FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
2813
2814      simple_ogg_page__init(&page);
2815      if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
2816         simple_ogg_page__clear(&page);
2817         return; /* state already set */
2818      }
2819
2820      if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
2821         encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
2822         simple_ogg_page__clear(&page);
2823         return;
2824      }
2825
2826      for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
2827         FLAC__uint64 xx;
2828         unsigned x;
2829         xx = encoder->private_->seek_table->points[i].sample_number;
2830         b[7] = (FLAC__byte)xx; xx >>= 8;
2831         b[6] = (FLAC__byte)xx; xx >>= 8;
2832         b[5] = (FLAC__byte)xx; xx >>= 8;
2833         b[4] = (FLAC__byte)xx; xx >>= 8;
2834         b[3] = (FLAC__byte)xx; xx >>= 8;
2835         b[2] = (FLAC__byte)xx; xx >>= 8;
2836         b[1] = (FLAC__byte)xx; xx >>= 8;
2837         b[0] = (FLAC__byte)xx; xx >>= 8;
2838         xx = encoder->private_->seek_table->points[i].stream_offset;
2839         b[15] = (FLAC__byte)xx; xx >>= 8;
2840         b[14] = (FLAC__byte)xx; xx >>= 8;
2841         b[13] = (FLAC__byte)xx; xx >>= 8;
2842         b[12] = (FLAC__byte)xx; xx >>= 8;
2843         b[11] = (FLAC__byte)xx; xx >>= 8;
2844         b[10] = (FLAC__byte)xx; xx >>= 8;
2845         b[9] = (FLAC__byte)xx; xx >>= 8;
2846         b[8] = (FLAC__byte)xx; xx >>= 8;
2847         x = encoder->private_->seek_table->points[i].frame_samples;
2848         b[17] = (FLAC__byte)x; x >>= 8;
2849         b[16] = (FLAC__byte)x; x >>= 8;
2850         memcpy(p, b, 18);
2851      }
2852
2853      if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
2854         simple_ogg_page__clear(&page);
2855         return; /* state already set */
2856      }
2857      simple_ogg_page__clear(&page);
2858   }
2859}
2860#endif
2861
2862FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
2863{
2864   FLAC__uint16 crc;
2865   FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
2866
2867   /*
2868    * Accumulate raw signal to the MD5 signature
2869    */
2870   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)) {
2871      encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2872      return false;
2873   }
2874
2875   /*
2876    * Process the frame header and subframes into the frame bitbuffer
2877    */
2878   if(!process_subframes_(encoder, is_fractional_block)) {
2879      /* the above function sets the state for us in case of an error */
2880      return false;
2881   }
2882
2883   /*
2884    * Zero-pad the frame to a byte_boundary
2885    */
2886   if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
2887      encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2888      return false;
2889   }
2890
2891   /*
2892    * CRC-16 the whole thing
2893    */
2894   FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
2895   if(
2896      !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
2897      !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
2898   ) {
2899      encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
2900      return false;
2901   }
2902
2903   /*
2904    * Write it
2905    */
2906   if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
2907      /* the above function sets the state for us in case of an error */
2908      return false;
2909   }
2910
2911   /*
2912    * Get ready for the next frame
2913    */
2914   encoder->private_->current_sample_number = 0;
2915   encoder->private_->current_frame_number++;
2916   encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
2917
2918   return true;
2919}
2920
2921FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
2922{
2923   FLAC__FrameHeader frame_header;
2924   unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
2925   FLAC__bool do_independent, do_mid_side;
2926
2927   /*
2928    * Calculate the min,max Rice partition orders
2929    */
2930   if(is_fractional_block) {
2931      max_partition_order = 0;
2932   }
2933   else {
2934      max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
2935      max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
2936   }
2937   min_partition_order = min(min_partition_order, max_partition_order);
2938
2939   /*
2940    * Setup the frame
2941    */
2942   frame_header.blocksize = encoder->protected_->blocksize;
2943   frame_header.sample_rate = encoder->protected_->sample_rate;
2944   frame_header.channels = encoder->protected_->channels;
2945   frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
2946   frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
2947   frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
2948   frame_header.number.frame_number = encoder->private_->current_frame_number;
2949
2950   /*
2951    * Figure out what channel assignments to try
2952    */
2953   if(encoder->protected_->do_mid_side_stereo) {
2954      if(encoder->protected_->loose_mid_side_stereo) {
2955         if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
2956            do_independent = true;
2957            do_mid_side = true;
2958         }
2959         else {
2960            do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
2961            do_mid_side = !do_independent;
2962         }
2963      }
2964      else {
2965         do_independent = true;
2966         do_mid_side = true;
2967      }
2968   }
2969   else {
2970      do_independent = true;
2971      do_mid_side = false;
2972   }
2973
2974   FLAC__ASSERT(do_independent || do_mid_side);
2975
2976   /*
2977    * Check for wasted bits; set effective bps for each subframe
2978    */
2979   if(do_independent) {
2980      for(channel = 0; channel < encoder->protected_->channels; channel++) {
2981         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
2982         encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
2983         encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
2984      }
2985   }
2986   if(do_mid_side) {
2987      FLAC__ASSERT(encoder->protected_->channels == 2);
2988      for(channel = 0; channel < 2; channel++) {
2989         const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
2990         encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
2991         encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
2992      }
2993   }
2994
2995   /*
2996    * First do a normal encoding pass of each independent channel
2997    */
2998   if(do_independent) {
2999      for(channel = 0; channel < encoder->protected_->channels; channel++) {
3000         if(!
3001            process_subframe_(
3002               encoder,
3003               min_partition_order,
3004               max_partition_order,
3005               &frame_header,
3006               encoder->private_->subframe_bps[channel],
3007               encoder->private_->integer_signal[channel],
3008               encoder->private_->subframe_workspace_ptr[channel],
3009               encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
3010               encoder->private_->residual_workspace[channel],
3011               encoder->private_->best_subframe+channel,
3012               encoder->private_->best_subframe_bits+channel
3013            )
3014         )
3015            return false;
3016      }
3017   }
3018
3019   /*
3020    * Now do mid and side channels if requested
3021    */
3022   if(do_mid_side) {
3023      FLAC__ASSERT(encoder->protected_->channels == 2);
3024
3025      for(channel = 0; channel < 2; channel++) {
3026         if(!
3027            process_subframe_(
3028               encoder,
3029               min_partition_order,
3030               max_partition_order,
3031               &frame_header,
3032               encoder->private_->subframe_bps_mid_side[channel],
3033               encoder->private_->integer_signal_mid_side[channel],
3034               encoder->private_->subframe_workspace_ptr_mid_side[channel],
3035               encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
3036               encoder->private_->residual_workspace_mid_side[channel],
3037               encoder->private_->best_subframe_mid_side+channel,
3038               encoder->private_->best_subframe_bits_mid_side+channel
3039            )
3040         )
3041            return false;
3042      }
3043   }
3044
3045   /*
3046    * Compose the frame bitbuffer
3047    */
3048   if(do_mid_side) {
3049      unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
3050      FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
3051      FLAC__ChannelAssignment channel_assignment;
3052
3053      FLAC__ASSERT(encoder->protected_->channels == 2);
3054
3055      if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
3056         channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
3057      }
3058      else {
3059         unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
3060         unsigned min_bits;
3061         int ca;
3062
3063         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
3064         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE   == 1);
3065         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE  == 2);
3066         FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE    == 3);
3067         FLAC__ASSERT(do_independent && do_mid_side);
3068
3069         /* We have to figure out which channel assignent results in the smallest frame */
3070         bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits         [1];
3071         bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE  ] = encoder->private_->best_subframe_bits         [0] + encoder->private_->best_subframe_bits_mid_side[1];
3072         bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits         [1] + encoder->private_->best_subframe_bits_mid_side[1];
3073         bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE   ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
3074
3075         channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
3076         min_bits = bits[channel_assignment];
3077         for(ca = 1; ca <= 3; ca++) {
3078            if(bits[ca] < min_bits) {
3079               min_bits = bits[ca];
3080               channel_assignment = (FLAC__ChannelAssignment)ca;
3081            }
3082         }
3083      }
3084
3085      frame_header.channel_assignment = channel_assignment;
3086
3087      if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3088         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3089         return false;
3090      }
3091
3092      switch(channel_assignment) {
3093         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3094            left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3095            right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3096            break;
3097         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3098            left_subframe  = &encoder->private_->subframe_workspace         [0][encoder->private_->best_subframe         [0]];
3099            right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3100            break;
3101         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3102            left_subframe  = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3103            right_subframe = &encoder->private_->subframe_workspace         [1][encoder->private_->best_subframe         [1]];
3104            break;
3105         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3106            left_subframe  = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
3107            right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
3108            break;
3109         default:
3110            FLAC__ASSERT(0);
3111      }
3112
3113      switch(channel_assignment) {
3114         case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
3115            left_bps  = encoder->private_->subframe_bps         [0];
3116            right_bps = encoder->private_->subframe_bps         [1];
3117            break;
3118         case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
3119            left_bps  = encoder->private_->subframe_bps         [0];
3120            right_bps = encoder->private_->subframe_bps_mid_side[1];
3121            break;
3122         case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
3123            left_bps  = encoder->private_->subframe_bps_mid_side[1];
3124            right_bps = encoder->private_->subframe_bps         [1];
3125            break;
3126         case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
3127            left_bps  = encoder->private_->subframe_bps_mid_side[0];
3128            right_bps = encoder->private_->subframe_bps_mid_side[1];
3129            break;
3130         default:
3131            FLAC__ASSERT(0);
3132      }
3133
3134      /* note that encoder_add_subframe_ sets the state for us in case of an error */
3135      if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
3136         return false;
3137      if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
3138         return false;
3139   }
3140   else {
3141      if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
3142         encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3143         return false;
3144      }
3145
3146      for(channel = 0; channel < encoder->protected_->channels; channel++) {
3147         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)) {
3148            /* the above function sets the state for us in case of an error */
3149            return false;
3150         }
3151      }
3152   }
3153
3154   if(encoder->protected_->loose_mid_side_stereo) {
3155      encoder->private_->loose_mid_side_stereo_frame_count++;
3156      if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
3157         encoder->private_->loose_mid_side_stereo_frame_count = 0;
3158   }
3159
3160   encoder->private_->last_channel_assignment = frame_header.channel_assignment;
3161
3162   return true;
3163}
3164
3165FLAC__bool process_subframe_(
3166   FLAC__StreamEncoder *encoder,
3167   unsigned min_partition_order,
3168   unsigned max_partition_order,
3169   const FLAC__FrameHeader *frame_header,
3170   unsigned subframe_bps,
3171   const FLAC__int32 integer_signal[],
3172   FLAC__Subframe *subframe[2],
3173   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
3174   FLAC__int32 *residual[2],
3175   unsigned *best_subframe,
3176   unsigned *best_bits
3177)
3178{
3179#ifndef FLAC__INTEGER_ONLY_LIBRARY
3180   FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3181#else
3182   FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
3183#endif
3184#ifndef FLAC__INTEGER_ONLY_LIBRARY
3185   FLAC__double lpc_residual_bits_per_sample;
3186   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 */
3187   FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
3188   unsigned min_lpc_order, max_lpc_order, lpc_order;
3189   unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
3190#endif
3191   unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
3192   unsigned rice_parameter;
3193   unsigned _candidate_bits, _best_bits;
3194   unsigned _best_subframe;
3195   /* only use RICE2 partitions if stream bps > 16 */
3196   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;
3197
3198   FLAC__ASSERT(frame_header->blocksize > 0);
3199
3200   /* verbatim subframe is the baseline against which we measure other compressed subframes */
3201   _best_subframe = 0;
3202   if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
3203      _best_bits = UINT_MAX;
3204   else
3205      _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3206
3207   if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
3208      unsigned signal_is_constant = false;
3209      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);
3210      /* check for constant subframe */
3211      if(
3212         !encoder->private_->disable_constant_subframes &&
3213#ifndef FLAC__INTEGER_ONLY_LIBRARY
3214         fixed_residual_bits_per_sample[1] == 0.0
3215#else
3216         fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
3217#endif
3218      ) {
3219         /* the above means it's possible all samples are the same value; now double-check it: */
3220         unsigned i;
3221         signal_is_constant = true;
3222         for(i = 1; i < frame_header->blocksize; i++) {
3223            if(integer_signal[0] != integer_signal[i]) {
3224               signal_is_constant = false;
3225               break;
3226            }
3227         }
3228      }
3229      if(signal_is_constant) {
3230         _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
3231         if(_candidate_bits < _best_bits) {
3232            _best_subframe = !_best_subframe;
3233            _best_bits = _candidate_bits;
3234         }
3235      }
3236      else {
3237         if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
3238            /* encode fixed */
3239            if(encoder->protected_->do_exhaustive_model_search) {
3240               min_fixed_order = 0;
3241               max_fixed_order = FLAC__MAX_FIXED_ORDER;
3242            }
3243            else {
3244               min_fixed_order = max_fixed_order = guess_fixed_order;
3245            }
3246            if(max_fixed_order >= frame_header->blocksize)
3247               max_fixed_order = frame_header->blocksize - 1;
3248            for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
3249#ifndef FLAC__INTEGER_ONLY_LIBRARY
3250               if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
3251                  continue; /* don't even try */
3252               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 */
3253#else
3254               if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
3255                  continue; /* don't even try */
3256               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 */
3257#endif
3258               rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3259               if(rice_parameter >= rice_parameter_limit) {
3260#ifdef DEBUG_VERBOSE
3261                  fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
3262#endif
3263                  rice_parameter = rice_parameter_limit - 1;
3264               }
3265               _candidate_bits =
3266                  evaluate_fixed_subframe_(
3267                     encoder,
3268                     integer_signal,
3269                     residual[!_best_subframe],
3270                     encoder->private_->abs_residual_partition_sums,
3271                     encoder->private_->raw_bits_per_partition,
3272                     frame_header->blocksize,
3273                     subframe_bps,
3274                     fixed_order,
3275                     rice_parameter,
3276                     rice_parameter_limit,
3277                     min_partition_order,
3278                     max_partition_order,
3279                     encoder->protected_->do_escape_coding,
3280                     encoder->protected_->rice_parameter_search_dist,
3281                     subframe[!_best_subframe],
3282                     partitioned_rice_contents[!_best_subframe]
3283                  );
3284               if(_candidate_bits < _best_bits) {
3285                  _best_subframe = !_best_subframe;
3286                  _best_bits = _candidate_bits;
3287               }
3288            }
3289         }
3290
3291#ifndef FLAC__INTEGER_ONLY_LIBRARY
3292         /* encode lpc */
3293         if(encoder->protected_->max_lpc_order > 0) {
3294            if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
3295               max_lpc_order = frame_header->blocksize-1;
3296            else
3297               max_lpc_order = encoder->protected_->max_lpc_order;
3298            if(max_lpc_order > 0) {
3299               unsigned a;
3300               for (a = 0; a < encoder->protected_->num_apodizations; a++) {
3301                  FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
3302                  encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
3303                  /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
3304                  if(autoc[0] != 0.0) {
3305                     FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
3306                     if(encoder->protected_->do_exhaustive_model_search) {
3307                        min_lpc_order = 1;
3308                     }
3309                     else {
3310                        const unsigned guess_lpc_order =
3311                           FLAC__lpc_compute_best_order(
3312                              lpc_error,
3313                              max_lpc_order,
3314                              frame_header->blocksize,
3315                              subframe_bps + (
3316                                 encoder->protected_->do_qlp_coeff_prec_search?
3317                                    FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
3318                                    encoder->protected_->qlp_coeff_precision
3319                              )
3320                           );
3321                        min_lpc_order = max_lpc_order = guess_lpc_order;
3322                     }
3323                     if(max_lpc_order >= frame_header->blocksize)
3324                        max_lpc_order = frame_header->blocksize - 1;
3325                     for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
3326                        lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
3327                        if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
3328                           continue; /* don't even try */
3329                        rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
3330                        rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
3331                        if(rice_parameter >= rice_parameter_limit) {
3332#ifdef DEBUG_VERBOSE
3333                           fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
3334#endif
3335                           rice_parameter = rice_parameter_limit - 1;
3336                        }
3337                        if(encoder->protected_->do_qlp_coeff_prec_search) {
3338                           min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
3339                           /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
3340                           if(subframe_bps <= 17) {
3341                              max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
3342                              max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
3343                           }
3344                           else
3345                              max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
3346                        }
3347                        else {
3348                           min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
3349                        }
3350                        for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
3351                           _candidate_bits =
3352                              evaluate_lpc_subframe_(
3353                                 encoder,
3354                                 integer_signal,
3355                                 residual[!_best_subframe],
3356                                 encoder->private_->abs_residual_partition_sums,
3357                                 encoder->private_->raw_bits_per_partition,
3358                                 encoder->private_->lp_coeff[lpc_order-1],
3359                                 frame_header->blocksize,
3360                                 subframe_bps,
3361                                 lpc_order,
3362                                 qlp_coeff_precision,
3363                                 rice_parameter,
3364                                 rice_parameter_limit,
3365                                 min_partition_order,
3366                                 max_partition_order,
3367                                 encoder->protected_->do_escape_coding,
3368                                 encoder->protected_->rice_parameter_search_dist,
3369                                 subframe[!_best_subframe],
3370                                 partitioned_rice_contents[!_best_subframe]
3371                              );
3372                           if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
3373                              if(_candidate_bits < _best_bits) {
3374                                 _best_subframe = !_best_subframe;
3375                                 _best_bits = _candidate_bits;
3376                              }
3377                           }
3378                        }
3379                     }
3380                  }
3381               }
3382            }
3383         }
3384#endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
3385      }
3386   }
3387
3388   /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
3389   if(_best_bits == UINT_MAX) {
3390      FLAC__ASSERT(_best_subframe == 0);
3391      _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
3392   }
3393
3394   *best_subframe = _best_subframe;
3395   *best_bits = _best_bits;
3396
3397   return true;
3398}
3399
3400FLAC__bool add_subframe_(
3401   FLAC__StreamEncoder *encoder,
3402   unsigned blocksize,
3403   unsigned subframe_bps,
3404   const FLAC__Subframe *subframe,
3405   FLAC__BitWriter *frame
3406)
3407{
3408   switch(subframe->type) {
3409      case FLAC__SUBFRAME_TYPE_CONSTANT:
3410         if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
3411            encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3412            return false;
3413         }
3414         break;
3415      case FLAC__SUBFRAME_TYPE_FIXED:
3416         if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
3417            encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3418            return false;
3419         }
3420         break;
3421      case FLAC__SUBFRAME_TYPE_LPC:
3422         if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
3423            encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3424            return false;
3425         }
3426         break;
3427      case FLAC__SUBFRAME_TYPE_VERBATIM:
3428         if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
3429            encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
3430            return false;
3431         }
3432         break;
3433      default:
3434         FLAC__ASSERT(0);
3435   }
3436
3437   return true;
3438}
3439
3440#define SPOTCHECK_ESTIMATE 0
3441#if SPOTCHECK_ESTIMATE
3442static void spotcheck_subframe_estimate_(
3443   FLAC__StreamEncoder *encoder,
3444   unsigned blocksize,
3445   unsigned subframe_bps,
3446   const FLAC__Subframe *subframe,
3447   unsigned estimate
3448)
3449{
3450   FLAC__bool ret;
3451   FLAC__BitWriter *frame = FLAC__bitwriter_new();
3452   if(frame == 0) {
3453      fprintf(stderr, "EST: can't allocate frame\n");
3454      return;
3455   }
3456   if(!FLAC__bitwriter_init(frame)) {
3457      fprintf(stderr, "EST: can't init frame\n");
3458      return;
3459   }
3460   ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
3461   FLAC__ASSERT(ret);
3462   {
3463      const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
3464      if(estimate != actual)
3465         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);
3466   }
3467   FLAC__bitwriter_delete(frame);
3468}
3469#endif
3470
3471unsigned evaluate_constant_subframe_(
3472   FLAC__StreamEncoder *encoder,
3473   const FLAC__int32 signal,
3474   unsigned blocksize,
3475   unsigned subframe_bps,
3476   FLAC__Subframe *subframe
3477)
3478{
3479   unsigned estimate;
3480   subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
3481   subframe->data.constant.value = signal;
3482
3483   estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
3484
3485#if SPOTCHECK_ESTIMATE
3486   spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3487#else
3488   (void)encoder, (void)blocksize;
3489#endif
3490
3491   return estimate;
3492}
3493
3494unsigned evaluate_fixed_subframe_(
3495   FLAC__StreamEncoder *encoder,
3496   const FLAC__int32 signal[],
3497   FLAC__int32 residual[],
3498   FLAC__uint64 abs_residual_partition_sums[],
3499   unsigned raw_bits_per_partition[],
3500   unsigned blocksize,
3501   unsigned subframe_bps,
3502   unsigned order,
3503   unsigned rice_parameter,
3504   unsigned rice_parameter_limit,
3505   unsigned min_partition_order,
3506   unsigned max_partition_order,
3507   FLAC__bool do_escape_coding,
3508   unsigned rice_parameter_search_dist,
3509   FLAC__Subframe *subframe,
3510   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3511)
3512{
3513   unsigned i, residual_bits, estimate;
3514   const unsigned residual_samples = blocksize - order;
3515
3516   FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
3517
3518   subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
3519
3520   subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3521   subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3522   subframe->data.fixed.residual = residual;
3523
3524   residual_bits =
3525      find_best_partition_order_(
3526         encoder->private_,
3527         residual,
3528         abs_residual_partition_sums,
3529         raw_bits_per_partition,
3530         residual_samples,
3531         order,
3532         rice_parameter,
3533         rice_parameter_limit,
3534         min_partition_order,
3535         max_partition_order,
3536         subframe_bps,
3537         do_escape_coding,
3538         rice_parameter_search_dist,
3539         &subframe->data.fixed.entropy_coding_method
3540      );
3541
3542   subframe->data.fixed.order = order;
3543   for(i = 0; i < order; i++)
3544      subframe->data.fixed.warmup[i] = signal[i];
3545
3546   estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
3547
3548#if SPOTCHECK_ESTIMATE
3549   spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3550#endif
3551
3552   return estimate;
3553}
3554
3555#ifndef FLAC__INTEGER_ONLY_LIBRARY
3556unsigned evaluate_lpc_subframe_(
3557   FLAC__StreamEncoder *encoder,
3558   const FLAC__int32 signal[],
3559   FLAC__int32 residual[],
3560   FLAC__uint64 abs_residual_partition_sums[],
3561   unsigned raw_bits_per_partition[],
3562   const FLAC__real lp_coeff[],
3563   unsigned blocksize,
3564   unsigned subframe_bps,
3565   unsigned order,
3566   unsigned qlp_coeff_precision,
3567   unsigned rice_parameter,
3568   unsigned rice_parameter_limit,
3569   unsigned min_partition_order,
3570   unsigned max_partition_order,
3571   FLAC__bool do_escape_coding,
3572   unsigned rice_parameter_search_dist,
3573   FLAC__Subframe *subframe,
3574   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
3575)
3576{
3577   FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
3578   unsigned i, residual_bits, estimate;
3579   int quantization, ret;
3580   const unsigned residual_samples = blocksize - order;
3581
3582   /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
3583   if(subframe_bps <= 16) {
3584      FLAC__ASSERT(order > 0);
3585      FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
3586      qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
3587   }
3588
3589   ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
3590   if(ret != 0)
3591      return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
3592
3593   if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
3594      if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
3595         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3596      else
3597         encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3598   else
3599      encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
3600
3601   subframe->type = FLAC__SUBFRAME_TYPE_LPC;
3602
3603   subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
3604   subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
3605   subframe->data.lpc.residual = residual;
3606
3607   residual_bits =
3608      find_best_partition_order_(
3609         encoder->private_,
3610         residual,
3611         abs_residual_partition_sums,
3612         raw_bits_per_partition,
3613         residual_samples,
3614         order,
3615         rice_parameter,
3616         rice_parameter_limit,
3617         min_partition_order,
3618         max_partition_order,
3619         subframe_bps,
3620         do_escape_coding,
3621         rice_parameter_search_dist,
3622         &subframe->data.lpc.entropy_coding_method
3623      );
3624
3625   subframe->data.lpc.order = order;
3626   subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
3627   subframe->data.lpc.quantization_level = quantization;
3628   memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
3629   for(i = 0; i < order; i++)
3630      subframe->data.lpc.warmup[i] = signal[i];
3631
3632   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;
3633
3634#if SPOTCHECK_ESTIMATE
3635   spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3636#endif
3637
3638   return estimate;
3639}
3640#endif
3641
3642unsigned evaluate_verbatim_subframe_(
3643   FLAC__StreamEncoder *encoder,
3644   const FLAC__int32 signal[],
3645   unsigned blocksize,
3646   unsigned subframe_bps,
3647   FLAC__Subframe *subframe
3648)
3649{
3650   unsigned estimate;
3651
3652   subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
3653
3654   subframe->data.verbatim.data = signal;
3655
3656   estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
3657
3658#if SPOTCHECK_ESTIMATE
3659   spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
3660#else
3661   (void)encoder;
3662#endif
3663
3664   return estimate;
3665}
3666
3667unsigned find_best_partition_order_(
3668   FLAC__StreamEncoderPrivate *private_,
3669   const FLAC__int32 residual[],
3670   FLAC__uint64 abs_residual_partition_sums[],
3671   unsigned raw_bits_per_partition[],
3672   unsigned residual_samples,
3673   unsigned predictor_order,
3674   unsigned rice_parameter,
3675   unsigned rice_parameter_limit,
3676   unsigned min_partition_order,
3677   unsigned max_partition_order,
3678   unsigned bps,
3679   FLAC__bool do_escape_coding,
3680   unsigned rice_parameter_search_dist,
3681   FLAC__EntropyCodingMethod *best_ecm
3682)
3683{
3684   unsigned residual_bits, best_residual_bits = 0;
3685   unsigned best_parameters_index = 0;
3686   unsigned best_partition_order = 0;
3687   const unsigned blocksize = residual_samples + predictor_order;
3688
3689   max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
3690   min_partition_order = min(min_partition_order, max_partition_order);
3691
3692   precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
3693
3694   if(do_escape_coding)
3695      precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
3696
3697   {
3698      int partition_order;
3699      unsigned sum;
3700
3701      for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
3702         if(!
3703            set_partitioned_rice_(
3704#ifdef EXACT_RICE_BITS_CALCULATION
3705               residual,
3706#endif
3707               abs_residual_partition_sums+sum,
3708               raw_bits_per_partition+sum,
3709               residual_samples,
3710               predictor_order,
3711               rice_parameter,
3712               rice_parameter_limit,
3713               rice_parameter_search_dist,
3714               (unsigned)partition_order,
3715               do_escape_coding,
3716               &private_->partitioned_rice_contents_extra[!best_parameters_index],
3717               &residual_bits
3718            )
3719         )
3720         {
3721            FLAC__ASSERT(best_residual_bits != 0);
3722            break;
3723         }
3724         sum += 1u << partition_order;
3725         if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
3726            best_residual_bits = residual_bits;
3727            best_parameters_index = !best_parameters_index;
3728            best_partition_order = partition_order;
3729         }
3730      }
3731   }
3732
3733   best_ecm->data.partitioned_rice.order = best_partition_order;
3734
3735   {
3736      /*
3737       * We are allowed to de-const the pointer based on our special
3738       * knowledge; it is const to the outside world.
3739       */
3740      FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
3741      unsigned partition;
3742
3743      /* save best parameters and raw_bits */
3744      FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
3745      memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
3746      if(do_escape_coding)
3747         memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
3748      /*
3749       * Now need to check if the type should be changed to
3750       * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
3751       * size of the rice parameters.
3752       */
3753      for(partition = 0; partition < (1u<<best_partition_order); partition++) {
3754         if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
3755            best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
3756            break;
3757         }
3758      }
3759   }
3760
3761   return best_residual_bits;
3762}
3763
3764#if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3765extern void precompute_partition_info_sums_32bit_asm_ia32_(
3766   const FLAC__int32 residual[],
3767   FLAC__uint64 abs_residual_partition_sums[],
3768   unsigned blocksize,
3769   unsigned predictor_order,
3770   unsigned min_partition_order,
3771   unsigned max_partition_order
3772);
3773#endif
3774
3775void precompute_partition_info_sums_(
3776   const FLAC__int32 residual[],
3777   FLAC__uint64 abs_residual_partition_sums[],
3778   unsigned residual_samples,
3779   unsigned predictor_order,
3780   unsigned min_partition_order,
3781   unsigned max_partition_order,
3782   unsigned bps
3783)
3784{
3785   const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
3786   unsigned partitions = 1u << max_partition_order;
3787
3788   FLAC__ASSERT(default_partition_samples > predictor_order);
3789
3790#if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
3791   /* slightly pessimistic but still catches all common cases */
3792   /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3793   if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3794      precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
3795      return;
3796   }
3797#endif
3798
3799   /* first do max_partition_order */
3800   {
3801      unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
3802      /* slightly pessimistic but still catches all common cases */
3803      /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
3804      if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
3805         FLAC__uint32 abs_residual_partition_sum;
3806
3807         for(partition = residual_sample = 0; partition < partitions; partition++) {
3808            end += default_partition_samples;
3809            abs_residual_partition_sum = 0;
3810            for( ; residual_sample < end; residual_sample++)
3811               abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3812            abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3813         }
3814      }
3815      else { /* have to pessimistically use 64 bits for accumulator */
3816         FLAC__uint64 abs_residual_partition_sum;
3817
3818         for(partition = residual_sample = 0; partition < partitions; partition++) {
3819            end += default_partition_samples;
3820            abs_residual_partition_sum = 0;
3821            for( ; residual_sample < end; residual_sample++)
3822               abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
3823            abs_residual_partition_sums[partition] = abs_residual_partition_sum;
3824         }
3825      }
3826   }
3827
3828   /* now merge partitions for lower orders */
3829   {
3830      unsigned from_partition = 0, to_partition = partitions;
3831      int partition_order;
3832      for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
3833         unsigned i;
3834         partitions >>= 1;
3835         for(i = 0; i < partitions; i++) {
3836            abs_residual_partition_sums[to_partition++] =
3837               abs_residual_partition_sums[from_partition  ] +
3838               abs_residual_partition_sums[from_partition+1];
3839            from_partition += 2;
3840         }
3841      }
3842   }
3843}
3844
3845void precompute_partition_info_escapes_(
3846   const FLAC__int32 residual[],
3847   unsigned raw_bits_per_partition[],
3848   unsigned residual_samples,
3849   unsigned predictor_order,
3850   unsigned min_partition_order,
3851   unsigned max_partition_order
3852)
3853{
3854   int partition_order;
3855   unsigned from_partition, to_partition = 0;
3856   const unsigned blocksize = residual_samples + predictor_order;
3857
3858   /* first do max_partition_order */
3859   for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
3860      FLAC__int32 r;
3861      FLAC__uint32 rmax;
3862      unsigned partition, partition_sample, partition_samples, residual_sample;
3863      const unsigned partitions = 1u << partition_order;
3864      const unsigned default_partition_samples = blocksize >> partition_order;
3865
3866      FLAC__ASSERT(default_partition_samples > predictor_order);
3867
3868      for(partition = residual_sample = 0; partition < partitions; partition++) {
3869         partition_samples = default_partition_samples;
3870         if(partition == 0)
3871            partition_samples -= predictor_order;
3872         rmax = 0;
3873         for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
3874            r = residual[residual_sample++];
3875            /* OPT: maybe faster: rmax |= r ^ (r>>31) */
3876            if(r < 0)
3877               rmax |= ~r;
3878            else
3879               rmax |= r;
3880         }
3881         /* now we know all residual values are in the range [-rmax-1,rmax] */
3882         raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
3883      }
3884      to_partition = partitions;
3885      break; /*@@@ yuck, should remove the 'for' loop instead */
3886   }
3887
3888   /* now merge partitions for lower orders */
3889   for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
3890      unsigned m;
3891      unsigned i;
3892      const unsigned partitions = 1u << partition_order;
3893      for(i = 0; i < partitions; i++) {
3894         m = raw_bits_per_partition[from_partition];
3895         from_partition++;
3896         raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
3897         from_partition++;
3898         to_partition++;
3899      }
3900   }
3901}
3902
3903#ifdef EXACT_RICE_BITS_CALCULATION
3904static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3905   const unsigned rice_parameter,
3906   const unsigned partition_samples,
3907   const FLAC__int32 *residual
3908)
3909{
3910   unsigned i, partition_bits =
3911      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 */
3912      (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
3913   ;
3914   for(i = 0; i < partition_samples; i++)
3915      partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
3916   return partition_bits;
3917}
3918#else
3919static FLaC__INLINE unsigned count_rice_bits_in_partition_(
3920   const unsigned rice_parameter,
3921   const unsigned partition_samples,
3922   const FLAC__uint64 abs_residual_partition_sum
3923)
3924{
3925   return
3926      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 */
3927      (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
3928      (
3929         rice_parameter?
3930            (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
3931            : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
3932      )
3933      - (partition_samples >> 1)
3934      /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
3935       * The actual number of bits used is closer to the sum(for all i in the partition) of  abs(residual[i])>>(rice_parameter-1)
3936       * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
3937       * So the subtraction term tries to guess how many extra bits were contributed.
3938       * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
3939       */
3940   ;
3941}
3942#endif
3943
3944FLAC__bool set_partitioned_rice_(
3945#ifdef EXACT_RICE_BITS_CALCULATION
3946   const FLAC__int32 residual[],
3947#endif
3948   const FLAC__uint64 abs_residual_partition_sums[],
3949   const unsigned raw_bits_per_partition[],
3950   const unsigned residual_samples,
3951   const unsigned predictor_order,
3952   const unsigned suggested_rice_parameter,
3953   const unsigned rice_parameter_limit,
3954   const unsigned rice_parameter_search_dist,
3955   const unsigned partition_order,
3956   const FLAC__bool search_for_escapes,
3957   FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
3958   unsigned *bits
3959)
3960{
3961   unsigned rice_parameter, partition_bits;
3962   unsigned best_partition_bits, best_rice_parameter = 0;
3963   unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
3964   unsigned *parameters, *raw_bits;
3965#ifdef ENABLE_RICE_PARAMETER_SEARCH
3966   unsigned min_rice_parameter, max_rice_parameter;
3967#else
3968   (void)rice_parameter_search_dist;
3969#endif
3970
3971   FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3972   FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
3973
3974   FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
3975   parameters = partitioned_rice_contents->parameters;
3976   raw_bits = partitioned_rice_contents->raw_bits;
3977
3978   if(partition_order == 0) {
3979      best_partition_bits = (unsigned)(-1);
3980#ifdef ENABLE_RICE_PARAMETER_SEARCH
3981      if(rice_parameter_search_dist) {
3982         if(suggested_rice_parameter < rice_parameter_search_dist)
3983            min_rice_parameter = 0;
3984         else
3985            min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
3986         max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
3987         if(max_rice_parameter >= rice_parameter_limit) {
3988#ifdef DEBUG_VERBOSE
3989            fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
3990#endif
3991            max_rice_parameter = rice_parameter_limit - 1;
3992         }
3993      }
3994      else
3995         min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
3996
3997      for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
3998#else
3999         rice_parameter = suggested_rice_parameter;
4000#endif
4001#ifdef EXACT_RICE_BITS_CALCULATION
4002         partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
4003#else
4004         partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
4005#endif
4006         if(partition_bits < best_partition_bits) {
4007            best_rice_parameter = rice_parameter;
4008            best_partition_bits = partition_bits;
4009         }
4010#ifdef ENABLE_RICE_PARAMETER_SEARCH
4011      }
4012#endif
4013      if(search_for_escapes) {
4014         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;
4015         if(partition_bits <= best_partition_bits) {
4016            raw_bits[0] = raw_bits_per_partition[0];
4017            best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4018            best_partition_bits = partition_bits;
4019         }
4020         else
4021            raw_bits[0] = 0;
4022      }
4023      parameters[0] = best_rice_parameter;
4024      bits_ += best_partition_bits;
4025   }
4026   else {
4027      unsigned partition, residual_sample;
4028      unsigned partition_samples;
4029      FLAC__uint64 mean, k;
4030      const unsigned partitions = 1u << partition_order;
4031      for(partition = residual_sample = 0; partition < partitions; partition++) {
4032         partition_samples = (residual_samples+predictor_order) >> partition_order;
4033         if(partition == 0) {
4034            if(partition_samples <= predictor_order)
4035               return false;
4036            else
4037               partition_samples -= predictor_order;
4038         }
4039         mean = abs_residual_partition_sums[partition];
4040         /* we are basically calculating the size in bits of the
4041          * average residual magnitude in the partition:
4042          *   rice_parameter = floor(log2(mean/partition_samples))
4043          * 'mean' is not a good name for the variable, it is
4044          * actually the sum of magnitudes of all residual values
4045          * in the partition, so the actual mean is
4046          * mean/partition_samples
4047          */
4048         for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
4049            ;
4050         if(rice_parameter >= rice_parameter_limit) {
4051#ifdef DEBUG_VERBOSE
4052            fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
4053#endif
4054            rice_parameter = rice_parameter_limit - 1;
4055         }
4056
4057         best_partition_bits = (unsigned)(-1);
4058#ifdef ENABLE_RICE_PARAMETER_SEARCH
4059         if(rice_parameter_search_dist) {
4060            if(rice_parameter < rice_parameter_search_dist)
4061               min_rice_parameter = 0;
4062            else
4063               min_rice_parameter = rice_parameter - rice_parameter_search_dist;
4064            max_rice_parameter = rice_parameter + rice_parameter_search_dist;
4065            if(max_rice_parameter >= rice_parameter_limit) {
4066#ifdef DEBUG_VERBOSE
4067               fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
4068#endif
4069               max_rice_parameter = rice_parameter_limit - 1;
4070            }
4071         }
4072         else
4073            min_rice_parameter = max_rice_parameter = rice_parameter;
4074
4075         for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
4076#endif
4077#ifdef EXACT_RICE_BITS_CALCULATION
4078            partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
4079#else
4080            partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
4081#endif
4082            if(partition_bits < best_partition_bits) {
4083               best_rice_parameter = rice_parameter;
4084               best_partition_bits = partition_bits;
4085            }
4086#ifdef ENABLE_RICE_PARAMETER_SEARCH
4087         }
4088#endif
4089         if(search_for_escapes) {
4090            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;
4091            if(partition_bits <= best_partition_bits) {
4092               raw_bits[partition] = raw_bits_per_partition[partition];
4093               best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
4094               best_partition_bits = partition_bits;
4095            }
4096            else
4097               raw_bits[partition] = 0;
4098         }
4099         parameters[partition] = best_rice_parameter;
4100         bits_ += best_partition_bits;
4101         residual_sample += partition_samples;
4102      }
4103   }
4104
4105   *bits = bits_;
4106   return true;
4107}
4108
4109unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
4110{
4111   unsigned i, shift;
4112   FLAC__int32 x = 0;
4113
4114   for(i = 0; i < samples && !(x&1); i++)
4115      x |= signal[i];
4116
4117   if(x == 0) {
4118      shift = 0;
4119   }
4120   else {
4121      for(shift = 0; !(x&1); shift++)
4122         x >>= 1;
4123   }
4124
4125   if(shift > 0) {
4126      for(i = 0; i < samples; i++)
4127          signal[i] >>= shift;
4128   }
4129
4130   return shift;
4131}
4132
4133void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4134{
4135   unsigned channel;
4136
4137   for(channel = 0; channel < channels; channel++)
4138      memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
4139
4140   fifo->tail += wide_samples;
4141
4142   FLAC__ASSERT(fifo->tail <= fifo->size);
4143}
4144
4145void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
4146{
4147   unsigned channel;
4148   unsigned sample, wide_sample;
4149   unsigned tail = fifo->tail;
4150
4151   sample = input_offset * channels;
4152   for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
4153      for(channel = 0; channel < channels; channel++)
4154         fifo->data[channel][tail] = input[sample++];
4155      tail++;
4156   }
4157   fifo->tail = tail;
4158
4159   FLAC__ASSERT(fifo->tail <= fifo->size);
4160}
4161
4162FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4163{
4164   FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4165   const size_t encoded_bytes = encoder->private_->verify.output.bytes;
4166   (void)decoder;
4167
4168   if(encoder->private_->verify.needs_magic_hack) {
4169      FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
4170      *bytes = FLAC__STREAM_SYNC_LENGTH;
4171      memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
4172      encoder->private_->verify.needs_magic_hack = false;
4173   }
4174   else {
4175      if(encoded_bytes == 0) {
4176         /*
4177          * If we get here, a FIFO underflow has occurred,
4178          * which means there is a bug somewhere.
4179          */
4180         FLAC__ASSERT(0);
4181         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
4182      }
4183      else if(encoded_bytes < *bytes)
4184         *bytes = encoded_bytes;
4185      memcpy(buffer, encoder->private_->verify.output.data, *bytes);
4186      encoder->private_->verify.output.data += *bytes;
4187      encoder->private_->verify.output.bytes -= *bytes;
4188   }
4189
4190   return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
4191}
4192
4193FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
4194{
4195   FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
4196   unsigned channel;
4197   const unsigned channels = frame->header.channels;
4198   const unsigned blocksize = frame->header.blocksize;
4199   const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
4200
4201   (void)decoder;
4202
4203   for(channel = 0; channel < channels; channel++) {
4204      if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
4205         unsigned i, sample = 0;
4206         FLAC__int32 expect = 0, got = 0;
4207
4208         for(i = 0; i < blocksize; i++) {
4209            if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
4210               sample = i;
4211               expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
4212               got = (FLAC__int32)buffer[channel][i];
4213               break;
4214            }
4215         }
4216         FLAC__ASSERT(i < blocksize);
4217         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
4218         encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
4219         encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
4220         encoder->private_->verify.error_stats.channel = channel;
4221         encoder->private_->verify.error_stats.sample = sample;
4222         encoder->private_->verify.error_stats.expected = expect;
4223         encoder->private_->verify.error_stats.got = got;
4224         encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
4225         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
4226      }
4227   }
4228   /* dequeue the frame from the fifo */
4229   encoder->private_->verify.input_fifo.tail -= blocksize;
4230   FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
4231   for(channel = 0; channel < channels; channel++)
4232      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]));
4233   return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
4234}
4235
4236void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
4237{
4238   (void)decoder, (void)metadata, (void)client_data;
4239}
4240
4241void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
4242{
4243   FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
4244   (void)decoder, (void)status;
4245   encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
4246}
4247
4248FLAC__StreamEncoderReadStatus file_read_callback_(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
4249{
4250   (void)client_data;
4251
4252   *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
4253   if (*bytes == 0) {
4254      if (feof(encoder->private_->file))
4255         return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
4256      else if (ferror(encoder->private_->file))
4257         return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
4258   }
4259   return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
4260}
4261
4262FLAC__StreamEncoderSeekStatus file_seek_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
4263{
4264   (void)client_data;
4265
4266   if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
4267      return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
4268   else
4269      return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
4270}
4271
4272FLAC__StreamEncoderTellStatus file_tell_callback_(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
4273{
4274   off_t offset;
4275
4276   (void)client_data;
4277
4278   offset = ftello(encoder->private_->file);
4279
4280   if(offset < 0) {
4281      return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
4282   }
4283   else {
4284      *absolute_byte_offset = (FLAC__uint64)offset;
4285      return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
4286   }
4287}
4288
4289#ifdef FLAC__VALGRIND_TESTING
4290static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
4291{
4292   size_t ret = fwrite(ptr, size, nmemb, stream);
4293   if(!ferror(stream))
4294      fflush(stream);
4295   return ret;
4296}
4297#else
4298#define local__fwrite fwrite
4299#endif
4300
4301FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
4302{
4303   (void)client_data, (void)current_frame;
4304
4305   if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
4306      FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
4307#if FLAC__HAS_OGG
4308         /* We would like to be able to use 'samples > 0' in the
4309          * clause here but currently because of the nature of our
4310          * Ogg writing implementation, 'samples' is always 0 (see
4311          * ogg_encoder_aspect.c).  The downside is extra progress
4312          * callbacks.
4313          */
4314         encoder->private_->is_ogg? true :
4315#endif
4316         samples > 0
4317      );
4318      if(call_it) {
4319         /* NOTE: We have to add +bytes, +samples, and +1 to the stats
4320          * because at this point in the callback chain, the stats
4321          * have not been updated.  Only after we return and control
4322          * gets back to write_frame_() are the stats updated
4323          */
4324         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);
4325      }
4326      return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
4327   }
4328   else
4329      return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
4330}
4331
4332/*
4333 * This will forcibly set stdout to binary mode (for OSes that require it)
4334 */
4335FILE *get_binary_stdout_(void)
4336{
4337#if 0
4338    /* if something breaks here it is probably due to the presence or
4339    * absence of an underscore before the identifiers 'setmode',
4340    * 'fileno', and/or 'O_BINARY'; check your system header files.
4341    */
4342#if defined _MSC_VER || defined __MINGW32__
4343   _setmode(_fileno(stdout), _O_BINARY);
4344#elif defined __CYGWIN__
4345   /* almost certainly not needed for any modern Cygwin, but let's be safe... */
4346   setmode(_fileno(stdout), _O_BINARY);
4347#elif defined __EMX__
4348   setmode(fileno(stdout), O_BINARY);
4349#endif
4350#endif
4351   return stdout;
4352}
src/lib/libflac/libflac/stream_encoder_framing.c
r0r14135
1/* libFLAC - Free Lossless Audio Codec library
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * - Neither the name of the Xiph.org Foundation nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#if HAVE_CONFIG_H
33#  include <config.h>
34#endif
35
36#include <stdio.h>
37#include <string.h> /* for strlen() */
38#include "private/stream_encoder_framing.h"
39#include "private/crc.h"
40#include "flac/assert.h"
41
42#ifdef max
43#undef max
44#endif
45#define max(x,y) ((x)>(y)?(x):(y))
46
47static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
48static 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);
49
50FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
51{
52   unsigned i, j;
53   const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
54
55   if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
56      return false;
57
58   if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
59      return false;
60
61   /*
62    * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
63    */
64   i = metadata->length;
65   if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
66      FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
67      i -= metadata->data.vorbis_comment.vendor_string.length;
68      i += vendor_string_length;
69   }
70   FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
71   if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
72      return false;
73
74   switch(metadata->type) {
75      case FLAC__METADATA_TYPE_STREAMINFO:
76         FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
77         if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
78            return false;
79         FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
80         if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
81            return false;
82         FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
83         if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
84            return false;
85         FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
86         if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
87            return false;
88         FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
89         if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
90            return false;
91         FLAC__ASSERT(metadata->data.stream_info.channels > 0);
92         FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
93         if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
94            return false;
95         FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
96         FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
97         if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
98            return false;
99         if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
100            return false;
101         if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
102            return false;
103         break;
104      case FLAC__METADATA_TYPE_PADDING:
105         if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
106            return false;
107         break;
108      case FLAC__METADATA_TYPE_APPLICATION:
109         if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
110            return false;
111         if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
112            return false;
113         break;
114      case FLAC__METADATA_TYPE_SEEKTABLE:
115         for(i = 0; i < metadata->data.seek_table.num_points; i++) {
116            if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
117               return false;
118            if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
119               return false;
120            if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
121               return false;
122         }
123         break;
124      case FLAC__METADATA_TYPE_VORBIS_COMMENT:
125         if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
126            return false;
127         if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
128            return false;
129         if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
130            return false;
131         for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
132            if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
133               return false;
134            if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
135               return false;
136         }
137         break;
138      case FLAC__METADATA_TYPE_CUESHEET:
139         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
140         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))
141            return false;
142         if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
143            return false;
144         if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
145            return false;
146         if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
147            return false;
148         if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
149            return false;
150         for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
151            const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
152
153            if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
154               return false;
155            if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
156               return false;
157            FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
158            if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
159               return false;
160            if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
161               return false;
162            if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
163               return false;
164            if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
165               return false;
166            if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
167               return false;
168            for(j = 0; j < track->num_indices; j++) {
169               const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
170
171               if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
172                  return false;
173               if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
174                  return false;
175               if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
176                  return false;
177            }
178         }
179         break;
180      case FLAC__METADATA_TYPE_PICTURE:
181         {
182            size_t len;
183            if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
184               return false;
185            len = strlen(metadata->data.picture.mime_type);
186            if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
187               return false;
188            if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
189               return false;
190            len = strlen((const char *)metadata->data.picture.description);
191            if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
192               return false;
193            if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
194               return false;
195            if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
196               return false;
197            if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
198               return false;
199            if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
200               return false;
201            if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
202               return false;
203            if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
204               return false;
205            if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
206               return false;
207         }
208         break;
209      default:
210         if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
211            return false;
212         break;
213   }
214
215   FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
216   return true;
217}
218
219FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
220{
221   unsigned u, blocksize_hint, sample_rate_hint;
222   FLAC__byte crc;
223
224   FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
225
226   if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
227      return false;
228
229   if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
230      return false;
231
232   if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
233      return false;
234
235   FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
236   /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
237   FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
238   blocksize_hint = 0;
239   switch(header->blocksize) {
240      case   192: u = 1; break;
241      case   576: u = 2; break;
242      case  1152: u = 3; break;
243      case  2304: u = 4; break;
244      case  4608: u = 5; break;
245      case   256: u = 8; break;
246      case   512: u = 9; break;
247      case  1024: u = 10; break;
248      case  2048: u = 11; break;
249      case  4096: u = 12; break;
250      case  8192: u = 13; break;
251      case 16384: u = 14; break;
252      case 32768: u = 15; break;
253      default:
254         if(header->blocksize <= 0x100)
255            blocksize_hint = u = 6;
256         else
257            blocksize_hint = u = 7;
258         break;
259   }
260   if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
261      return false;
262
263   FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
264   sample_rate_hint = 0;
265   switch(header->sample_rate) {
266      case  88200: u = 1; break;
267      case 176400: u = 2; break;
268      case 192000: u = 3; break;
269      case   8000: u = 4; break;
270      case  16000: u = 5; break;
271      case  22050: u = 6; break;
272      case  24000: u = 7; break;
273      case  32000: u = 8; break;
274      case  44100: u = 9; break;
275      case  48000: u = 10; break;
276      case  96000: u = 11; break;
277      default:
278         if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
279            sample_rate_hint = u = 12;
280         else if(header->sample_rate % 10 == 0)
281            sample_rate_hint = u = 14;
282         else if(header->sample_rate <= 0xffff)
283            sample_rate_hint = u = 13;
284         else
285            u = 0;
286         break;
287   }
288   if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
289      return false;
290
291   FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
292   switch(header->channel_assignment) {
293      case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
294         u = header->channels - 1;
295         break;
296      case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
297         FLAC__ASSERT(header->channels == 2);
298         u = 8;
299         break;
300      case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
301         FLAC__ASSERT(header->channels == 2);
302         u = 9;
303         break;
304      case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
305         FLAC__ASSERT(header->channels == 2);
306         u = 10;
307         break;
308      default:
309         FLAC__ASSERT(0);
310   }
311   if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
312      return false;
313
314   FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
315   switch(header->bits_per_sample) {
316      case 8 : u = 1; break;
317      case 12: u = 2; break;
318      case 16: u = 4; break;
319      case 20: u = 5; break;
320      case 24: u = 6; break;
321      default: u = 0; break;
322   }
323   if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
324      return false;
325
326   if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
327      return false;
328
329   if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
330      if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
331         return false;
332   }
333   else {
334      if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
335         return false;
336   }
337
338   if(blocksize_hint)
339      if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
340         return false;
341
342   switch(sample_rate_hint) {
343      case 12:
344         if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
345            return false;
346         break;
347      case 13:
348         if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
349            return false;
350         break;
351      case 14:
352         if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
353            return false;
354         break;
355   }
356
357   /* write the CRC */
358   if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
359      return false;
360   if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
361      return false;
362
363   return true;
364}
365
366FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
367{
368   FLAC__bool ok;
369
370   ok =
371      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) &&
372      (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
373      FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
374   ;
375
376   return ok;
377}
378
379FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
380{
381   unsigned i;
382
383   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))
384      return false;
385   if(wasted_bits)
386      if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
387         return false;
388
389   for(i = 0; i < subframe->order; i++)
390      if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
391         return false;
392
393   if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
394      return false;
395   switch(subframe->entropy_coding_method.type) {
396      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
397      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
398         if(!add_residual_partitioned_rice_(
399            bw,
400            subframe->residual,
401            residual_samples,
402            subframe->order,
403            subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
404            subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
405            subframe->entropy_coding_method.data.partitioned_rice.order,
406            /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
407         ))
408            return false;
409         break;
410      default:
411         FLAC__ASSERT(0);
412   }
413
414   return true;
415}
416
417FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
418{
419   unsigned i;
420
421   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))
422      return false;
423   if(wasted_bits)
424      if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
425         return false;
426
427   for(i = 0; i < subframe->order; i++)
428      if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
429         return false;
430
431   if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
432      return false;
433   if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
434      return false;
435   for(i = 0; i < subframe->order; i++)
436      if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
437         return false;
438
439   if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
440      return false;
441   switch(subframe->entropy_coding_method.type) {
442      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
443      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
444         if(!add_residual_partitioned_rice_(
445            bw,
446            subframe->residual,
447            residual_samples,
448            subframe->order,
449            subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
450            subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
451            subframe->entropy_coding_method.data.partitioned_rice.order,
452            /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
453         ))
454            return false;
455         break;
456      default:
457         FLAC__ASSERT(0);
458   }
459
460   return true;
461}
462
463FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
464{
465   unsigned i;
466   const FLAC__int32 *signal = subframe->data;
467
468   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))
469      return false;
470   if(wasted_bits)
471      if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
472         return false;
473
474   for(i = 0; i < samples; i++)
475      if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
476         return false;
477
478   return true;
479}
480
481FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
482{
483   if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
484      return false;
485   switch(method->type) {
486      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
487      case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
488         if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
489            return false;
490         break;
491      default:
492         FLAC__ASSERT(0);
493   }
494   return true;
495}
496
497FLAC__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)
498{
499   const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
500   const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
501
502   if(partition_order == 0) {
503      unsigned i;
504
505      if(raw_bits[0] == 0) {
506         if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
507            return false;
508         if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
509            return false;
510      }
511      else {
512         FLAC__ASSERT(rice_parameters[0] == 0);
513         if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
514            return false;
515         if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
516            return false;
517         for(i = 0; i < residual_samples; i++) {
518            if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
519               return false;
520         }
521      }
522      return true;
523   }
524   else {
525      unsigned i, j, k = 0, k_last = 0;
526      unsigned partition_samples;
527      const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
528      for(i = 0; i < (1u<<partition_order); i++) {
529         partition_samples = default_partition_samples;
530         if(i == 0)
531            partition_samples -= predictor_order;
532         k += partition_samples;
533         if(raw_bits[i] == 0) {
534            if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
535               return false;
536            if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
537               return false;
538         }
539         else {
540            if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
541               return false;
542            if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
543               return false;
544            for(j = k_last; j < k; j++) {
545               if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
546                  return false;
547            }
548         }
549         k_last = k;
550      }
551      return true;
552   }
553}
src/lib/lib.mak
r14134r14135
2020   $(LIBOBJ)/zlib \
2121   $(LIBOBJ)/softfloat \
2222   $(LIBOBJ)/libjpeg \
23   $(LIBOBJ)/libflac \
24   $(LIBOBJ)/libflacpp \
2325
2426
2527
r14134r14135
265267   $(CC) $(CDEFS) $(CCOMFLAGS) $(CONLYFLAGS) -I$(LIBSRC)/libjpeg -c $< -o $@
266268
267269
270#-------------------------------------------------
271# libflac library objects
272#-------------------------------------------------
273
274include $(LIBSRC)/libflac/libflac.mak
275include $(LIBSRC)/libflac/libflac++.mak
276
src/lib/util/chd.c
r14134r14135
4141#include "avcomp.h"
4242#include "md5.h"
4343#include "sha1.h"
44#include "cdrom.h"
4445#include <zlib.h>
4546#include <time.h>
4647#include <stddef.h>
4748#include <stdlib.h>
4849#include <new>
4950
51#include "../../lib/libflac/include/flac/all.h"
5052
5153
52
5354/***************************************************************************
5455    DEBUGGING
5556***************************************************************************/
r14134r14135
7071
7172#define MAP_ENTRY_FLAG_TYPE_MASK   0x0f      /* what type of hunk */
7273#define MAP_ENTRY_FLAG_NO_CRC      0x10      /* no CRC is present */
74#define MAP_ENTRY_FLAG_HALF_HUNK   0x20      /* only the first half of this hunk is included in the SHA1 calculation (workaround for CD track padding issue) */
7375
74#define MAP_ENTRY_TYPE_INVALID      0x00      /* invalid type */
75#define MAP_ENTRY_TYPE_COMPRESSED   0x01      /* standard compression */
76#define MAP_ENTRY_TYPE_UNCOMPRESSED   0x02      /* uncompressed data */
77#define MAP_ENTRY_TYPE_MINI         0x03      /* mini: use offset as raw data */
78#define MAP_ENTRY_TYPE_SELF_HUNK   0x04      /* same as another hunk in this file */
79#define MAP_ENTRY_TYPE_PARENT_HUNK   0x05      /* same as a hunk in the parent file */
76#define MAP_ENTRY_TYPE_INVALID              0x00      /* invalid type */
77#define MAP_ENTRY_TYPE_COMPRESSED           0x01      /* standard compression */
78#define MAP_ENTRY_TYPE_UNCOMPRESSED           0x02      /* uncompressed data */
79#define MAP_ENTRY_TYPE_MINI                 0x03      /* mini: use offset as raw data */
80#define MAP_ENTRY_TYPE_SELF_HUNK           0x04      /* same as another hunk in this file */
81#define MAP_ENTRY_TYPE_PARENT_HUNK           0x05      /* same as a hunk in the parent file */
82#define MAP_ENTRY_TYPE_2ND_COMPRESSED       0x06      /* compressed with secondary algorithm (usually FLAC CDDA) */
8083
8184#define CHD_V1_SECTOR_SIZE         512         /* size of a "sector" in the V1 header */
8285
r14134r14135
113116   chd_error   (*compress)(chd_file *chd, const void *src, UINT32 *complen); /* compress data */
114117   chd_error   (*decompress)(chd_file *chd, UINT32 complen, void *dst); /* decompress data */
115118   chd_error   (*config)(chd_file *chd, int param, void *config); /* configure */
119
120   chd_error   (*secondary_compress)(chd_file *chd, const void *src, UINT32 *complen); /* secondary compress data */
121   chd_error   (*secondary_decompress)(chd_file *chd, UINT32 complen, void *dst); /* secondary decompress data */
122
116123};
117124
118125
r14134r14135
249256/* internal hunk read/write */
250257static chd_error hunk_read_into_cache(chd_file *chd, UINT32 hunknum);
251258static chd_error hunk_read_into_memory(chd_file *chd, UINT32 hunknum, UINT8 *dest);
252static chd_error hunk_write_from_memory(chd_file *chd, UINT32 hunknum, const UINT8 *src);
259static chd_error hunk_write_from_memory(chd_file *chd, UINT32 hunknum, const UINT8 *src, int is_half_hunk = 0);
253260
254261/* internal map access */
255262static chd_error map_write_initial(core_file *file, chd_file *parent, const chd_header *header);
r14134r14135
275282static voidpf zlib_fast_alloc(voidpf opaque, uInt items, uInt size);
276283static void zlib_fast_free(voidpf opaque, voidpf address);
277284
285/* flac compression codec */
286static chd_error flac_codec_compress(chd_file *chd, const void *src, UINT32 *length, int swap);
287static chd_error flac_codec_compress_normal(chd_file *chd, const void *src, UINT32 *length);
288static chd_error flac_codec_decompress(chd_file *chd, UINT32 srclength, void *dest);
289
290
278291/* A/V compression codec */
279292static chd_error av_codec_init(chd_file *chd);
280293static void av_codec_free(chd_file *chd);
r14134r14135
300313      NULL,
301314      NULL,
302315      NULL,
316      NULL,
317      NULL,
303318      NULL
304319   },
305320
r14134r14135
312327      zlib_codec_free,
313328      zlib_codec_compress,
314329      zlib_codec_decompress,
330      NULL,
331      NULL,
315332      NULL
316333   },
317334
r14134r14135
324341      zlib_codec_free,
325342      zlib_codec_compress,
326343      zlib_codec_decompress,
344      NULL,
345      NULL,
327346      NULL
328347   },
329348
r14134r14135
336355      av_codec_free,
337356      av_codec_compress,
338357      av_codec_decompress,
339      av_codec_config
340   }
358      av_codec_config,
359      NULL,
360      NULL
361   },
362
363   /* zlib+ with FLAC compression */
364   {
365      CHDCOMPRESSION_ZLIB_PLUS_WITH_FLAC,
366      "zlib+ with FLAC",
367      FALSE,
368      zlib_codec_init,
369      zlib_codec_free,
370      zlib_codec_compress,
371      zlib_codec_decompress,
372      NULL,
373      flac_codec_compress_normal,
374      flac_codec_decompress,
375   },
341376};
342377
343378
r14134r14135
14211456    that is being compressed
14221457-------------------------------------------------*/
14231458
1424chd_error chd_compress_hunk(chd_file *chd, const void *data, double *curratio)
1459chd_error chd_compress_hunk(chd_file *chd, const void *data, double *curratio, int is_half_hunk)
14251460{
14261461   UINT32 thishunk = chd->comphunk++;
14271462   UINT64 sourceoffset = (UINT64)thishunk * (UINT64)chd->header.hunkbytes;
r14134r14135
14341469      return CHDERR_INVALID_STATE;
14351470
14361471   /* write out the hunk */
1437   err = hunk_write_from_memory(chd, thishunk, (const UINT8 *)data);
1472   err = hunk_write_from_memory(chd, thishunk, (const UINT8 *)data, is_half_hunk);
14381473   if (err != CHDERR_NONE)
14391474      return err;
14401475
r14134r14135
14441479
14451480   /* update the MD5/SHA1 */
14461481   bytestochecksum = chd->header.hunkbytes;
1482
1483   if (is_half_hunk)
1484   {
1485      bytestochecksum = bytestochecksum/2;
1486   }
1487
14471488   if (sourceoffset + chd->header.hunkbytes > chd->header.logicalbytes)
14481489   {
14491490      if (sourceoffset >= chd->header.logicalbytes)
r14134r14135
15521593   if (err != CHDERR_NONE)
15531594      return err;
15541595
1596   entry = &chd->map[thishunk];
1597
15551598   /* update the MD5/SHA1 */
15561599   if (hunkoffset < chd->header.logicalbytes)
15571600   {
15581601      UINT64 bytestochecksum = MIN(chd->header.hunkbytes, chd->header.logicalbytes - hunkoffset);
1602
1603      if (entry->flags & MAP_ENTRY_FLAG_HALF_HUNK)
1604      {
1605         bytestochecksum /= 2;
1606      }
1607
15591608      if (bytestochecksum > 0)
15601609      {
15611610         MD5Update(&chd->vermd5, chd->cache, bytestochecksum);
r14134r14135
15641613   }
15651614
15661615   /* validate the CRC if we have one */
1567   entry = &chd->map[thishunk];
15681616   if (!(entry->flags & MAP_ENTRY_FLAG_NO_CRC) && entry->crc != crc32(0, chd->cache, chd->header.hunkbytes))
15691617      return CHDERR_DECOMPRESSION_ERROR;
15701618
r14134r14135
19832031         if (err != CHDERR_NONE)
19842032            return err;
19852033         break;
2034
2035      case MAP_ENTRY_TYPE_2ND_COMPRESSED:
2036         /* read it into the decompression buffer */
2037         core_fseek(chd->file, entry->offset, SEEK_SET);
2038         bytes = core_fread(chd->file, chd->compressed, entry->length);
2039         if (bytes != entry->length)
2040            return CHDERR_READ_ERROR;
2041
2042         /* now decompress using the codec */
2043         err = CHDERR_NONE;
2044         if (chd->codecintf->secondary_decompress != NULL)
2045            err = (*chd->codecintf->secondary_decompress)(chd, entry->length, dest);
2046         if (err != CHDERR_NONE)
2047            return err;
2048         break;
2049
19862050   }
19872051   return CHDERR_NONE;
19882052}
r14134r14135
19932057    memory into a CHD
19942058-------------------------------------------------*/
19952059
1996static chd_error hunk_write_from_memory(chd_file *chd, UINT32 hunknum, const UINT8 *src)
2060
2061static chd_error hunk_write_from_memory(chd_file *chd, UINT32 hunknum, const UINT8 *src, int is_half_hunk)
19972062{
19982063   map_entry *entry = &chd->map[hunknum];
19992064   map_entry newentry;
r14134r14135
20012066   const void *data = src;
20022067   UINT32 bytes = 0, match;
20032068   chd_error err;
2069   bool is_likely_cd = false;
2070   int strategy = 0;
20042071
20052072   /* track the max */
20062073   if (hunknum > chd->maxhunk)
20072074      chd->maxhunk = hunknum;
20082075
20092076   /* first compute the CRC of the original data */
2077    newentry.flags = 0;
2078    newentry.length = 0;
2079    newentry.offset = 0;
20102080   newentry.crc = 0;
20112081   if (src != NULL)
20122082      newentry.crc = crc32(0, &src[0], chd->header.hunkbytes);
r14134r14135
20562126      }
20572127   }
20582128
2059   /* now try compressing the data */
2060   err = CHDERR_COMPRESSION_ERROR;
2061   if (chd->codecintf->compress != NULL)
2062      err = (*chd->codecintf->compress)(chd, src, &bytes);
2129   if (chd->codecintf->secondary_compress != NULL)
2130   {
2131      if (chd->header.hunkbytes == (CD_MAX_SECTOR_DATA+CD_MAX_SUBCODE_DATA) * CD_FRAMES_PER_HUNK)
2132         is_likely_cd = true;
20632133
2134      if (is_likely_cd)
2135      {
2136         int offset = 0;
2137         for (int frames=0;frames<CD_FRAMES_PER_HUNK;frames++)
2138         {
2139            int secoff;
2140            for (secoff=0;secoff<CD_MAX_SECTOR_DATA;secoff++)
2141            {
2142               offset++;
2143            }
2144            for (secoff=0;secoff<CD_MAX_SUBCODE_DATA;secoff++)
2145            {     
2146               if (src[offset]!=0x00)
2147                  is_likely_cd = false;
2148
2149               offset++;
2150            }
2151         }
2152      }
2153   }
2154
2155   if (is_likely_cd)
2156   {
2157      err = CHDERR_COMPRESSION_ERROR;
2158
2159      UINT8* tempram = (UINT8 *)malloc(chd->header.hunkbytes);
2160      UINT32 tempbytes = 0;
2161      chd_error temperror = err;
2162      int tempstrategy = 0;
2163
2164      /* try strategy 0 - zlib */
2165      if (chd->codecintf->compress != NULL)
2166      {
2167         err = (*chd->codecintf->compress)(chd, src, &bytes);
2168
2169         /* store current results and errors */
2170         memcpy(tempram, chd->compressed, bytes);
2171         tempbytes = bytes;
2172         temperror = err;
2173         tempstrategy = 0;
2174      }       
2175
2176      /* try strategy 1 - flac */
2177      if (chd->codecintf->secondary_compress != NULL)
2178      {
2179         strategy = 1;
2180         
2181         err = (*chd->codecintf->secondary_compress)(chd, src, &bytes);
2182
2183         /* check against previous compression attempt if that was successful */
2184         if (temperror == CHDERR_NONE)
2185         {
2186            /* if the previous compression was better, restore that ... */
2187            if (bytes>=tempbytes)
2188            {
2189               strategy = tempstrategy;
2190               memcpy(chd->compressed, tempram, tempbytes);
2191               bytes = tempbytes;
2192               err = temperror;
2193            }
2194         }
2195      }
2196
2197      free(tempram);
2198   }
2199   else
2200   {
2201      /* now try compressing the data */
2202      err = CHDERR_COMPRESSION_ERROR;
2203      if (chd->codecintf->compress != NULL)
2204         err = (*chd->codecintf->compress)(chd, src, &bytes);
2205   }
2206
20642207   /* if that worked, and we're lossy, decompress and CRC the result */
20652208   if (err == CHDERR_NONE && (chd->codecintf->lossy || src == NULL))
20662209   {
r14134r14135
20742217   {
20752218      data = chd->compressed;
20762219      newentry.length = bytes;
2077      newentry.flags = MAP_ENTRY_TYPE_COMPRESSED;
2220     
2221      if (strategy == 0)
2222      {
2223         newentry.flags = MAP_ENTRY_TYPE_COMPRESSED;
2224      }
2225      else if (strategy == 1)
2226      {
2227         newentry.flags = MAP_ENTRY_TYPE_2ND_COMPRESSED;
2228      }
20782229   }
20792230
20802231   /* otherwise, mark it uncompressed and use the original data */
r14134r14135
20842235      newentry.flags = MAP_ENTRY_TYPE_UNCOMPRESSED;
20852236   }
20862237
2238
20872239   /* if the data doesn't fit into the previous entry, make a new one at the eof */
20882240   newentry.offset = entry->offset;
20892241   if (newentry.offset == 0 || newentry.length > entry->length)
r14134r14135
20972249
20982250   /* update the entry in memory */
20992251write_entry:
2252
2253   if (is_half_hunk)
2254      newentry.flags |= MAP_ENTRY_FLAG_HALF_HUNK;
2255
21002256   *entry = newentry;
21012257
21022258   /* update the map on file */
r14134r14135
22462402      /* track the maximum offset */
22472403      for (j = 0; j < entries; j++)
22482404         if ((chd->map[i + j].flags & MAP_ENTRY_FLAG_TYPE_MASK) == MAP_ENTRY_TYPE_COMPRESSED ||
2405            (chd->map[i + j].flags & MAP_ENTRY_FLAG_TYPE_MASK) == MAP_ENTRY_TYPE_2ND_COMPRESSED ||
22492406            (chd->map[i + j].flags & MAP_ENTRY_FLAG_TYPE_MASK) == MAP_ENTRY_TYPE_UNCOMPRESSED)
22502407            maxoffset = MAX(maxoffset, chd->map[i + j].offset + chd->map[i + j].length);
22512408   }
r14134r14135
23852542      for (curentry = chd->crctable[crc % CRCMAP_HASH_SIZE]; curentry; curentry = curentry->next)
23862543      {
23872544         curhunk = curentry->hunknum;
2388         if (chd->map[curhunk].crc == crc && !(chd->map[curhunk].flags & MAP_ENTRY_FLAG_NO_CRC) && crcmap_verify_hunk_match(chd, curhunk, rawdata))
2545         if (chd->map[curhunk].crc == crc && !(chd->map[curhunk].flags & MAP_ENTRY_FLAG_NO_CRC) && !(chd->map[curhunk].flags & MAP_ENTRY_FLAG_HALF_HUNK) && crcmap_verify_hunk_match(chd, curhunk, rawdata))
23892546            return curhunk;
23902547      }
23912548      return NO_MATCH;
23922549   }
23932550
23942551   /* first see if the last match is a valid one */
2395   if (chd->comparehunk < chd->header.totalhunks && chd->map[chd->comparehunk].crc == crc && !(chd->map[chd->comparehunk].flags & MAP_ENTRY_FLAG_NO_CRC) &&
2552   if (chd->comparehunk < chd->header.totalhunks && chd->map[chd->comparehunk].crc == crc && !(chd->map[chd->comparehunk].flags & MAP_ENTRY_FLAG_NO_CRC) && !(chd->map[chd->comparehunk].flags & MAP_ENTRY_FLAG_HALF_HUNK) &&
23962553      memcmp(rawdata, chd->compare, chd->header.hunkbytes) == 0)
23972554      return chd->comparehunk;
23982555
23992556   /* scan through the CHD's hunk map looking for a match */
24002557   for (curhunk = 0; curhunk < lasthunk; curhunk++)
2401      if (chd->map[curhunk].crc == crc && !(chd->map[curhunk].flags & MAP_ENTRY_FLAG_NO_CRC) && crcmap_verify_hunk_match(chd, curhunk, rawdata))
2558      if (chd->map[curhunk].crc == crc && !(chd->map[curhunk].flags & MAP_ENTRY_FLAG_NO_CRC) && !(chd->map[curhunk].flags & MAP_ENTRY_FLAG_HALF_HUNK) && crcmap_verify_hunk_match(chd, curhunk, rawdata))
24022559         return curhunk;
24032560
24042561   return NO_MATCH;
r14134r14135
28653022      }
28663023}
28673024
3025/*-------------------------------------------------
3026    flac_codec_compress - compress data using the
3027    FLAC codec
3028-------------------------------------------------*/
28683029
28693030
3031const int INITIAL_BUFFER_SIZE = 0x20000;
3032const int INITIAL_GROW_SIZE = 0x20000;
3033
3034
3035struct flac_encoder_data
3036{
3037   FLAC__int32* pcm;
3038   FLAC__byte* tempbuffer;
3039   UINT8* flac_outputbuffer;
3040   size_t flac_outputbuffer_size;
3041   FLAC__uint64 flac_output_buffer_curpos;
3042   FLAC__uint64 flac_output_buffer_total;
3043};
3044
3045static FLAC__StreamEncoderWriteStatus flac_encoder_write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
3046{
3047   if (((flac_encoder_data*)client_data)->flac_output_buffer_curpos + bytes >= ((flac_encoder_data*)client_data)->flac_outputbuffer_size)
3048   {
3049      ((flac_encoder_data*)client_data)->flac_outputbuffer = (UINT8*)realloc(((flac_encoder_data*)client_data)->flac_outputbuffer, ((flac_encoder_data*)client_data)->flac_outputbuffer_size+INITIAL_GROW_SIZE);
3050      ((flac_encoder_data*)client_data)->flac_outputbuffer_size = ((flac_encoder_data*)client_data)->flac_outputbuffer_size+INITIAL_GROW_SIZE;
3051   }
3052
3053   memcpy(((flac_encoder_data*)client_data)->flac_outputbuffer+((flac_encoder_data*)client_data)->flac_output_buffer_curpos, buffer, bytes);
3054   if (((flac_encoder_data*)client_data)->flac_output_buffer_curpos+bytes > ((flac_encoder_data*)client_data)->flac_output_buffer_total)
3055      ((flac_encoder_data*)client_data)->flac_output_buffer_total=((flac_encoder_data*)client_data)->flac_output_buffer_curpos+bytes;
3056
3057   ((flac_encoder_data*)client_data)->flac_output_buffer_curpos+=bytes;
3058
3059   return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
3060}
3061
3062#define FLAC_HEADER_SIZE (86)
3063
3064static chd_error flac_codec_compress(chd_file *chd, const void *src, UINT32 *length, int swap)
3065{
3066   int FLAC_ENCODER_READSIZE = (CD_MAX_SECTOR_DATA/4);
3067   int FLAC_ENCODER_FULLSIZE = ((CD_MAX_SECTOR_DATA+CD_MAX_SUBCODE_DATA)/4);
3068
3069   flac_encoder_data flac_encoder_client;
3070   flac_encoder_data* flac_encoder_client_ptr = &flac_encoder_client;
3071   flac_encoder_client_ptr->flac_outputbuffer = (UINT8*)malloc(INITIAL_BUFFER_SIZE);
3072   flac_encoder_client_ptr->flac_outputbuffer_size = INITIAL_BUFFER_SIZE;
3073   flac_encoder_client_ptr->flac_output_buffer_curpos = 0;
3074   flac_encoder_client_ptr->flac_output_buffer_total = 0;
3075   flac_encoder_client_ptr->pcm=(FLAC__int32*)malloc(FLAC_ENCODER_READSIZE * 2 * 4);
3076   flac_encoder_client_ptr->tempbuffer=(FLAC__byte*)malloc(FLAC_ENCODER_READSIZE * 2 * 2);
3077
3078
3079
3080   FLAC__StreamEncoder *encoder = 0;
3081   FLAC__bool ok = true;
3082
3083   if((encoder = FLAC__stream_encoder_new()) == NULL)
3084   {
3085      printf("ERROR: allocating encoder\n");
3086      return CHDERR_COMPRESSION_ERROR;
3087   }
3088   
3089   ok &= FLAC__stream_encoder_set_verify(encoder, false); // we trust libFLAC ;-)
3090   ok &= FLAC__stream_encoder_set_compression_level(encoder, 8);
3091   ok &= FLAC__stream_encoder_set_channels(encoder, 2);
3092   ok &= FLAC__stream_encoder_set_bits_per_sample(encoder, 16);
3093   ok &= FLAC__stream_encoder_set_sample_rate(encoder, 44100);
3094   ok &= FLAC__stream_encoder_set_total_samples_estimate(encoder, 0);
3095   ok &= FLAC__stream_encoder_set_streamable_subset(encoder, false);
3096   ok &= FLAC__stream_encoder_set_blocksize(encoder, ((CD_MAX_SECTOR_DATA)*CD_FRAMES_PER_HUNK) );
3097   
3098   if (!ok)
3099   {
3100      printf("error setting up stream encoder\n");
3101      return CHDERR_COMPRESSION_ERROR;
3102   }
3103
3104   if  (FLAC__stream_encoder_init_stream(encoder, flac_encoder_write_callback, NULL, NULL, NULL, flac_encoder_client_ptr)  != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
3105   {
3106      printf("error initializing encoder\n");
3107      return CHDERR_COMPRESSION_ERROR;
3108   }
3109
3110   size_t left = (size_t)chd->header.hunkbytes;
3111   UINT8* srcdata = (UINT8*)src;
3112
3113   while(ok && left)
3114   {
3115      memcpy(flac_encoder_client_ptr->tempbuffer, srcdata, FLAC_ENCODER_READSIZE*4);
3116      srcdata += FLAC_ENCODER_FULLSIZE*4;
3117      {
3118         size_t i;
3119         for(i = 0; i < FLAC_ENCODER_READSIZE*2; i++)
3120         {
3121            if (!swap) flac_encoder_client_ptr->pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)flac_encoder_client_ptr->tempbuffer[2*i] << 8) | (FLAC__int16)flac_encoder_client_ptr->tempbuffer[2*i+1]);
3122            else       flac_encoder_client_ptr->pcm[i] = (FLAC__int32)(((FLAC__int16)(FLAC__int8)flac_encoder_client_ptr->tempbuffer[2*i+1] << 8) | (FLAC__int16)flac_encoder_client_ptr->tempbuffer[2*i]);
3123         }
3124     
3125         ok = FLAC__stream_encoder_process_interleaved(encoder, flac_encoder_client_ptr->pcm, FLAC_ENCODER_READSIZE);
3126      }
3127
3128
3129      left -= (FLAC_ENCODER_FULLSIZE*4);
3130   }
3131
3132   if (!ok)
3133   {
3134      printf("error encoding!\n");
3135      return CHDERR_COMPRESSION_ERROR;
3136   }
3137
3138   ok &= FLAC__stream_encoder_finish(encoder);
3139
3140   if (!ok)
3141   {
3142      printf("error finishing!\n");
3143      return CHDERR_COMPRESSION_ERROR;
3144   }
3145   
3146   int totalout = flac_encoder_client_ptr->flac_output_buffer_total-FLAC_HEADER_SIZE;
3147
3148   
3149
3150   FLAC__stream_encoder_delete(encoder);
3151
3152   if (totalout >= chd->header.hunkbytes)
3153   {
3154      free(flac_encoder_client_ptr->flac_outputbuffer);
3155      return CHDERR_COMPRESSION_ERROR;
3156   }
3157
3158   *length = totalout;
3159   memcpy(chd->compressed, flac_encoder_client_ptr->flac_outputbuffer+FLAC_HEADER_SIZE, flac_encoder_client_ptr->flac_output_buffer_total-FLAC_HEADER_SIZE);
3160
3161   free(flac_encoder_client_ptr->flac_outputbuffer);
3162   free(flac_encoder_client_ptr->pcm);
3163   free(flac_encoder_client_ptr->tempbuffer);
3164   return CHDERR_NONE;
3165}
3166
3167static chd_error flac_codec_compress_normal(chd_file *chd, const void *src, UINT32 *length)
3168{
3169   return flac_codec_compress(chd, src, length, 0);
3170}
3171
3172// this data is always the same for our blocks, so don't store it in the file.
3173static UINT8 flacHeader[FLAC_HEADER_SIZE] = {
3174   0x66, 0x4C, 0x61, 0x43, 0x00, 0x00, 0x00, 0x22, 0x12, 0x60, 0x12, 0x60,
3175   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xC4, 0x42, 0xF0, 0x00, 0x00,
3176   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3177   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x28, 0x20, 0x00,
3178   0x00, 0x00, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6E, 0x63, 0x65, 0x20,
3179   0x6C, 0x69, 0x62, 0x46, 0x4C, 0x41, 0x43, 0x20, 0x31, 0x2E, 0x32, 0x2E,
3180   0x31, 0x20, 0x32, 0x30, 0x30, 0x37, 0x30, 0x39, 0x31, 0x37, 0x00, 0x00,
3181   0x00, 0x00,
3182};
3183/*-------------------------------------------------
3184    flac_codec_decompress - decomrpess data using
3185    the FLAC codec
3186-------------------------------------------------*/
3187
3188
3189struct flac_decoder_data
3190{
3191   int readoffset;
3192   size_t readbuffersize;
3193   UINT8* readbuffer;
3194
3195   int writeoffset;
3196   INT16 tempbuffer[(CD_MAX_SECTOR_DATA * CD_FRAMES_PER_HUNK)/2];
3197   UINT64 amount_to_decode;
3198};
3199
3200FLAC__StreamDecoderWriteStatus flac_decoder_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data)
3201{
3202   
3203   int blocksize = frame->header.blocksize;
3204   int i = 0;
3205   while (blocksize && ((flac_decoder_data*)client_data)->amount_to_decode)
3206   {
3207      ((flac_decoder_data*)client_data)->tempbuffer[(((flac_decoder_data*)client_data)->writeoffset*2)+0] = buffer[0][i];
3208      ((flac_decoder_data*)client_data)->tempbuffer[(((flac_decoder_data*)client_data)->writeoffset*2)+1] =  buffer[1][i];
3209
3210      blocksize--;
3211      i++;
3212      ((flac_decoder_data*)client_data)->amount_to_decode-=4;
3213      ((flac_decoder_data*)client_data)->writeoffset++;
3214   }
3215   
3216   return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
3217}
3218
3219FLAC__StreamDecoderReadStatus flac_decoder_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
3220{
3221   size_t readsize = *bytes;
3222   size_t readbuffersize = ((flac_decoder_data*)client_data)->readbuffersize;
3223
3224   if ((((flac_decoder_data*)client_data)->readoffset + readsize) > readbuffersize)
3225   {
3226      readsize = ((flac_decoder_data*)client_data)->readbuffersize-((flac_decoder_data*)client_data)->readoffset;
3227   }
3228
3229   if (readsize==0) return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
3230
3231   memcpy(buffer, ((flac_decoder_data*)client_data)->readbuffer+((flac_decoder_data*)client_data)->readoffset, readsize);
3232
3233   ((flac_decoder_data*)client_data)->readoffset += readsize;
3234
3235   return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
3236}
3237
3238
3239
3240void flac_decoder_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
3241{
3242
3243}
3244
3245void flac_decoder_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
3246{
3247
3248}
3249
3250static chd_error flac_codec_decompress(chd_file *chd, UINT32 srclength, void *dest)
3251{
3252   FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
3253   flac_decoder_data flac_decoder_client;
3254   flac_decoder_data* flac_decoder_client_ptr = &flac_decoder_client;
3255
3256   flac_decoder_client_ptr->readoffset = 0;
3257
3258   flac_decoder_client_ptr->readbuffersize = srclength+FLAC_HEADER_SIZE;
3259   flac_decoder_client_ptr->readbuffer = (UINT8*)malloc(flac_decoder_client_ptr->readbuffersize);
3260   flac_decoder_client_ptr->amount_to_decode =  (CD_MAX_SECTOR_DATA*CD_FRAMES_PER_HUNK);
3261   int frames_to_decode = flac_decoder_client_ptr->amount_to_decode / CD_MAX_SECTOR_DATA;
3262           
3263   flac_decoder_client_ptr->writeoffset = 0;
3264
3265   memcpy(flac_decoder_client_ptr->readbuffer, flacHeader, FLAC_HEADER_SIZE);
3266   memcpy(flac_decoder_client_ptr->readbuffer+FLAC_HEADER_SIZE, chd->compressed, srclength);
3267
3268   if (!decoder)
3269   {
3270      printf("unable to create FLAC decoder\n");
3271      return CHDERR_READ_ERROR;
3272   }
3273
3274   if(FLAC__stream_decoder_init_stream(
3275      decoder,
3276      flac_decoder_read_callback,
3277      NULL,
3278      NULL,
3279      NULL,
3280      NULL,
3281      flac_decoder_write_callback,
3282      flac_decoder_metadata_callback,
3283      flac_decoder_error_callback,
3284      flac_decoder_client_ptr ) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
3285   {
3286      printf("unable to init FLAC decoder\n");
3287      return CHDERR_READ_ERROR;
3288   }
3289
3290   if (FLAC__stream_decoder_process_until_end_of_metadata(decoder) != FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM)
3291   {
3292      printf("Fail FLAC__stream_decoder_process_until_end_of_metadata\n");
3293      return CHDERR_READ_ERROR;
3294   }
3295
3296   /* only ever a single frame */
3297   if (FLAC__stream_decoder_process_single(decoder) != FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM)
3298   {
3299      printf("Fail FLAC__stream_decoder_process_until_end_of_metadata\n");
3300      return CHDERR_READ_ERROR;
3301   }
3302
3303   
3304   int srcoffset = 0;
3305   UINT8* dest2 = (UINT8*)dest;
3306   for (int frame = 0; frame<frames_to_decode;frame++)
3307   {
3308      int destoffset = frame * (CD_FRAME_SIZE);
3309               
3310
3311      int index;
3312
3313      for (index = 0; index < 2352; index += 2 )
3314      {
3315         dest2[ destoffset + index +1 ] = flac_decoder_client_ptr->tempbuffer[srcoffset] & 0xff;
3316         dest2[ destoffset + index ] = flac_decoder_client_ptr->tempbuffer[srcoffset] >> 8;
3317               
3318         srcoffset++;
3319      }
3320   }
3321   
3322
3323   if (FLAC__stream_decoder_finish (decoder) != true)
3324   {
3325      printf("unable to finish FLAC decoder\n");
3326      return CHDERR_READ_ERROR;
3327   }
3328
3329   FLAC__stream_decoder_delete(decoder);
3330   free(flac_decoder_client_ptr->readbuffer);
3331
3332   return CHDERR_NONE;
3333}
3334
3335
3336
3337
28703338/***************************************************************************
28713339    AV COMPRESSION CODEC
28723340***************************************************************************/
src/lib/util/chd.h
r14134r14135
149149#define CHDFLAGS_UNDEFINED         0xfffffffc
150150
151151/* compression types */
152#define CHDCOMPRESSION_NONE         0
153#define CHDCOMPRESSION_ZLIB         1
154#define CHDCOMPRESSION_ZLIB_PLUS   2
155#define CHDCOMPRESSION_AV         3
152#define CHDCOMPRESSION_NONE                 0
153#define CHDCOMPRESSION_ZLIB                 1
154#define CHDCOMPRESSION_ZLIB_PLUS           2
155#define CHDCOMPRESSION_AV                 3
156#define CHDCOMPRESSION_ZLIB_PLUS_WITH_FLAC  4
156157
157158/* A/V codec configuration parameters */
158159#define AV_CODEC_COMPRESS_CONFIG   1
r14134r14135
358359chd_error chd_compress_begin(chd_file *chd);
359360
360361/* compress the next hunk of data */
361chd_error chd_compress_hunk(chd_file *chd, const void *data, double *curratio);
362chd_error chd_compress_hunk(chd_file *chd, const void *data, double *curratio, int is_half_hunk = 0);
362363
363364/* finish compressing data to a CHD */
364365chd_error chd_compress_finish(chd_file *chd, int write_protect);
src/lib/util/cdrom.h
r14134r14135
5656#define CD_MAX_SUBCODE_DATA      (96)
5757
5858#define CD_FRAME_SIZE         (CD_MAX_SECTOR_DATA + CD_MAX_SUBCODE_DATA)
59#define CD_FRAMES_PER_HUNK      (4)
59#define CD_FRAMES_PER_HUNK      (8)
6060
6161#define CD_METADATA_WORDS      (1+(CD_MAX_TRACKS * 6))
6262
makefile
r14134r14135
632632
633633all: default tools
634634
635FLAC_LIB = $(OBJ)/libflac.a $(OBJ)/libflac++.a
635636
637FLAC_LIB = $(OBJ)/libflac.a $(OBJ)/libflac++.a
636638
637639#-------------------------------------------------
638640# defines needed by multiple make files
r14134r14135
725727# always recompile the version string
726728$(VERSIONOBJ): $(DRVLIBS) $(LIBOSD) $(LIBCPU) $(LIBEMU) $(LIBSOUND) $(LIBUTIL) $(EXPAT) $(ZLIB) $(SOFTFLOAT) $(FORMATS_LIB) $(LIBOCORE) $(RESFILE)
727729
728$(EMULATOR): $(VERSIONOBJ) $(EMUINFOOBJ) $(DRIVLISTOBJ) $(DEVLISTOBJ) $(DRVLIBS) $(LIBOSD) $(LIBCPU) $(LIBEMU) $(LIBDASM) $(LIBSOUND) $(LIBUTIL) $(EXPAT) $(SOFTFLOAT) $(JPEG_LIB) $(FORMATS_LIB) $(ZLIB) $(LIBOCORE) $(RESFILE)
730$(EMULATOR): $(VERSIONOBJ) $(EMUINFOOBJ) $(DRIVLISTOBJ) $(DEVLISTOBJ) $(DRVLIBS) $(LIBOSD) $(LIBCPU) $(LIBEMU) $(LIBDASM) $(LIBSOUND) $(LIBUTIL) $(EXPAT) $(SOFTFLOAT) $(JPEG_LIB) $(FLAC_LIB) $(FORMATS_LIB) $(ZLIB) $(LIBOCORE) $(RESFILE)
729731   @echo Linking $@...
730732   $(LD) $(LDFLAGS) $(LDFLAGSEMULATOR) $^ $(LIBS) -o $@
731733ifeq ($(TARGETOS),win32)

Previous 15994 Revisions Next


© 1998-2018 The MESS Team