mask mousewheel segv bug, mask opengl sw fallback read to ram, fix tiff config withou...
[goodguy/cinelerra.git] / cinelerra-5.1 / guicast / vframe.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2011 Adam Williams <broadcast at earthling dot net>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #include <errno.h>
23 #include <png.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdint.h>
27 #include <fcntl.h>
28 #include <sys/shm.h>
29 #include <sys/mman.h>
30
31 #include "bcbitmap.h"
32 #include "bchash.h"
33 #include "bcpbuffer.h"
34 #include "bcresources.h"
35 #include "bcsignals.h"
36 #include "bcsynchronous.h"
37 #include "bctexture.h"
38 #include "bcwindowbase.h"
39 #include "clip.h"
40 #include "bccmodels.h"
41 #include "vframe.h"
42
43 class PngReadFunction
44 {
45 public:
46         static void png_read_function(png_structp png_ptr,
47                         png_bytep data, png_size_t length)
48         {
49                 VFrame *frame = (VFrame*)png_get_io_ptr(png_ptr);
50                 if(frame->image_size - frame->image_offset < (long)length)
51                 {
52                         printf("PngReadFunction::png_read_function %d: overrun\n", __LINE__);
53                         length = frame->image_size - frame->image_offset;
54                 }
55
56                 memcpy(data, &frame->image[frame->image_offset], length);
57                 frame->image_offset += length;
58         };
59 };
60
61
62
63
64
65
66
67 VFrameScene::VFrameScene()
68 {
69 }
70
71 VFrameScene::~VFrameScene()
72 {
73 }
74
75
76
77
78
79
80
81 //static BCCounter counter;
82
83 VFramePng::VFramePng(unsigned char *png_data, double s)
84 {
85         long image_size =
86                 ((long)png_data[0] << 24) | ((long)png_data[1] << 16) |
87                 ((long)png_data[2] << 8)  |  (long)png_data[3];
88         if( !s ) s = BC_WindowBase::get_resources()->icon_scale;
89         read_png(png_data+4, image_size, s, s);
90 }
91
92 VFramePng::VFramePng(unsigned char *png_data, long image_size, double xs, double ys)
93 {
94         if( !xs ) xs = BC_WindowBase::get_resources()->icon_scale;
95         if( !ys ) ys = BC_WindowBase::get_resources()->icon_scale;
96         read_png(png_data, image_size, xs, ys);
97 }
98
99 VFramePng::~VFramePng()
100 {
101 }
102
103 VFrame *VFramePng::vframe_png(int fd, double xs, double ys)
104 {
105         struct stat st;
106         if( fstat(fd, &st) ) return 0;
107         long len = st.st_size;
108         if( !len ) return 0;
109         int w = 0, h = 0;
110         unsigned char *bfr = (unsigned char *)
111                 ::mmap (NULL, len, PROT_READ, MAP_SHARED, fd, 0);
112         if( bfr == MAP_FAILED ) return 0;
113         VFrame *vframe = new VFramePng(bfr, len, xs, ys);
114         if( (w=vframe->get_w()) <= 0 || (h=vframe->get_h()) <= 0 ||
115             vframe->get_data() == 0 ) { delete vframe;  vframe = 0; }
116         ::munmap(bfr, len);
117         return vframe;
118 }
119 VFrame *VFramePng::vframe_png(const char *png_path, double xs, double ys)
120 {
121         VFrame *vframe = 0;
122         int fd = ::open(png_path, O_RDONLY);
123         if( fd >= 0 ) {
124                 vframe = vframe_png(fd, xs, ys);
125                 ::close(fd);
126         }
127         return vframe;
128 }
129
130 VFrame::VFrame(VFrame &frame)
131 {
132         reset_parameters(1);
133         params = new BC_Hash;
134         use_shm = frame.use_shm;
135         allocate_data(0, -1, 0, 0, 0, frame.w, frame.h,
136                 frame.color_model, frame.bytes_per_line);
137         copy_vframe(&frame);
138 }
139
140
141 VFrame::VFrame(int w, int h, int color_model, long bytes_per_line)
142 {
143         reset_parameters(1);
144 //  use bytes_per_line == 0 to allocate default unshared
145         if( !bytes_per_line ) { bytes_per_line = -1;  use_shm = 0; }
146         params = new BC_Hash;
147         allocate_data(data, -1, 0, 0, 0, w, h,
148                 color_model, bytes_per_line);
149 }
150
151 VFrame::VFrame(unsigned char *data, int shmid, int w, int h,
152         int color_model, long bytes_per_line)
153 {
154         reset_parameters(1);
155         params = new BC_Hash;
156         allocate_data(data, shmid, 0, 0, 0, w, h,
157                 color_model, bytes_per_line);
158 }
159
160 VFrame::VFrame(unsigned char *data, int shmid,
161                 long y_offset, long u_offset, long v_offset,
162                 int w, int h, int color_model, long bytes_per_line)
163 {
164         reset_parameters(1);
165         params = new BC_Hash;
166         allocate_data(data, shmid, y_offset, u_offset, v_offset, w, h,
167                 color_model, bytes_per_line);
168 }
169
170 VFrame::VFrame(BC_Bitmap *bitmap, int w, int h,
171                  int color_model, long bytes_per_line)
172 {
173         reset_parameters(1);
174         params = new BC_Hash;
175         int shmid = 0;
176         unsigned char *data = 0;
177         if( bitmap->is_shared() )
178                 shmid = bitmap->get_shmid();
179         else
180                 data = bitmap->get_data();
181         allocate_data(data, shmid,
182                 bitmap->get_y_offset(),
183                 bitmap->get_u_offset(),
184                 bitmap->get_v_offset(),
185                 w, h, color_model, bytes_per_line);
186 }
187
188 VFrame::VFrame()
189 {
190         reset_parameters(1);
191         params = new BC_Hash;
192         this->color_model = BC_COMPRESSED;
193 }
194
195
196
197 VFrame::~VFrame()
198 {
199         clear_objects(1);
200 // Delete effect stack
201         prev_effects.remove_all_objects();
202         next_effects.remove_all_objects();
203         delete params;
204         delete scene;
205 }
206
207 int VFrame::equivalent(VFrame *src, int test_stacks)
208 {
209         return (src->get_color_model() == get_color_model() &&
210                 src->get_w() == get_w() &&
211                 src->get_h() == get_h() &&
212                 src->bytes_per_line == bytes_per_line &&
213                 (!test_stacks || equal_stacks(src)));
214 }
215
216 int VFrame::data_matches(VFrame *frame)
217 {
218         if(data && frame->get_data() &&
219                 frame->params_match(get_w(), get_h(), get_color_model()) &&
220                 get_data_size() == frame->get_data_size())
221         {
222                 int data_size = get_data_size();
223                 unsigned char *ptr1 = get_data();
224                 unsigned char *ptr2 = frame->get_data();
225                 for(int i = 0; i < data_size; i++)
226                 {
227                         if(*ptr1++ != *ptr2++) return 0;
228                 }
229                 return 1;
230         }
231         return 0;
232 }
233
234 // long VFrame::set_shm_offset(long offset)
235 // {
236 //      shm_offset = offset;
237 //      return 0;
238 // }
239 //
240 // long VFrame::get_shm_offset()
241 // {
242 //      return shm_offset;
243 // }
244 //
245 int VFrame::get_memory_type()
246 {
247         return memory_type;
248 }
249
250 int VFrame::params_match(int w, int h, int color_model)
251 {
252         return (this->w == w &&
253                 this->h == h &&
254                 this->color_model == color_model);
255 }
256
257
258 int VFrame::reset_parameters(int do_opengl)
259 {
260         status = 1;
261         scene = 0;
262         field2_offset = -1;
263         memory_type = VFrame::PRIVATE;
264 //      shm_offset = 0;
265         shmid = -1;
266         use_shm = 1;
267         bytes_per_line = 0;
268         data = 0;
269         rows = 0;
270         color_model = 0;
271         compressed_allocated = 0;
272         compressed_size = 0;   // Size of current image
273         w = 0;
274         h = 0;
275         y = u = v = a = 0;
276         y_offset = 0;
277         u_offset = 0;
278         v_offset = 0;
279         sequence_number = -1;
280         timestamp = -1.;
281         is_keyframe = 0;
282         pixel_rgb = 0x000000; // BLACK
283         pixel_yuv = 0x008080;
284         stipple = 0;
285
286         if(do_opengl)
287         {
288 // By default, anything is going to be done in RAM
289                 opengl_state = VFrame::RAM;
290                 pbuffer = 0;
291                 texture = 0;
292         }
293
294         prev_effects.set_array_delete();
295         next_effects.set_array_delete();
296         return 0;
297 }
298
299 int VFrame::clear_objects(int do_opengl)
300 {
301 // Remove texture
302         if(do_opengl)
303         {
304                 delete texture;
305                 texture = 0;
306
307                 delete pbuffer;
308                 pbuffer = 0;
309         }
310
311 #ifdef LEAKER
312 if( memory_type != VFrame::SHARED )
313   printf("==del %p from %p\n", data, __builtin_return_address(0));
314 #endif
315
316 // Delete data
317         switch(memory_type)
318         {
319                 case VFrame::PRIVATE:
320 // Memory check
321 // if(this->w * this->h > 1500 * 1100)
322 // printf("VFrame::clear_objects 2 this=%p data=%p\n", this, data);
323                         if(data)
324                         {
325 //printf("VFrame::clear_objects %d this=%p shmid=%p data=%p\n", __LINE__, this, shmid, data);
326                                 if(shmid >= 0)
327                                         shmdt(data);
328                                 else
329                                         free(data);
330 //PRINT_TRACE
331                         }
332
333                         data = 0;
334                         shmid = -1;
335                         break;
336
337                 case VFrame::SHMGET:
338                         if(data)
339                                 shmdt(data);
340                         data = 0;
341                         shmid = -1;
342                         break;
343         }
344
345 // Delete row pointers
346         switch(color_model)
347         {
348                 case BC_COMPRESSED:
349                 case BC_YUV410P:
350                 case BC_YUV411P:
351                 case BC_YUV420P:
352                 case BC_YUV420PI:
353                 case BC_YUV422P:
354                 case BC_YUV444P:
355                 case BC_RGB_FLOATP:
356                 case BC_RGBA_FLOATP:
357                 case BC_GBRP:
358                         break;
359
360                 default:
361                         delete [] rows;
362                         rows = 0;
363                         break;
364         }
365
366
367         return 0;
368 }
369
370 int VFrame::get_field2_offset()
371 {
372         return field2_offset;
373 }
374
375 int VFrame::set_field2_offset(int value)
376 {
377         this->field2_offset = value;
378         return 0;
379 }
380
381 void VFrame::set_keyframe(int value)
382 {
383         this->is_keyframe = value;
384 }
385
386 int VFrame::get_keyframe()
387 {
388         return is_keyframe;
389 }
390
391 void VFrame::get_temp(VFrame *&vfrm, int w, int h, int color_model)
392 {
393         if( vfrm && ( vfrm->color_model != color_model ||
394             vfrm->get_w() != w || vfrm->get_h() != h ) ) {
395                 delete vfrm;  vfrm = 0;
396         }
397         if( !vfrm ) vfrm = new VFrame(w, h, color_model, 0);
398 }
399
400
401
402 VFrameScene* VFrame::get_scene()
403 {
404         return scene;
405 }
406
407 int VFrame::calculate_bytes_per_pixel(int color_model)
408 {
409         return BC_CModels::calculate_pixelsize(color_model);
410 }
411
412 long VFrame::get_bytes_per_line()
413 {
414         return bytes_per_line;
415 }
416
417 long VFrame::get_data_size()
418 {
419         return calculate_data_size(w, h, bytes_per_line, color_model) - 4;
420 }
421
422 long VFrame::calculate_data_size(int w, int h, int bytes_per_line, int color_model)
423 {
424         return BC_CModels::calculate_datasize(w, h, bytes_per_line, color_model);
425 }
426
427 void VFrame::create_row_pointers()
428 {
429         int sz = w * h;
430         switch(color_model) {
431         case BC_YUV410P:
432                 if( this->v_offset ) break;
433                 this->y_offset = 0;
434                 this->u_offset = sz;
435                 this->v_offset = sz + w / 4 * h / 4;
436                 break;
437
438         case BC_YUV420P:
439         case BC_YUV420PI:
440         case BC_YUV411P:
441                 if( this->v_offset ) break;
442                 this->y_offset = 0;
443                 this->u_offset = sz;
444                 this->v_offset = sz + sz / 4;
445                 break;
446
447         case BC_YUV422P:
448                 if( this->v_offset ) break;
449                 this->y_offset = 0;
450                 this->u_offset = sz;
451                 this->v_offset = sz + sz / 2;
452                 break;
453         case BC_YUV444P:
454                 if( this->v_offset ) break;
455                 this->y_offset = 0;
456                 this->u_offset = sz;
457                 this->v_offset = sz + sz;
458                 break;
459         case BC_GBRP:
460                 if( this->v_offset ) break;
461                 this->y_offset = 0;
462                 this->u_offset = sz * sizeof(uint8_t);
463                 this->v_offset = 2 * sz * sizeof(uint8_t);
464                 break;
465         case BC_RGBA_FLOATP:
466                 if( this->v_offset || a ) break;
467                 a = this->data + 3 * sz * sizeof(float);
468         case BC_RGB_FLOATP:
469                 if( this->v_offset ) break;
470                 this->y_offset = 0;
471                 this->u_offset = sz * sizeof(float);
472                 this->v_offset = 2 * sz * sizeof(float);
473                 break;
474
475         default:
476                 rows = new unsigned char*[h];
477                 for(int i = 0; i < h; i++)
478                         rows[i] = &this->data[i * this->bytes_per_line];
479                 return;
480         }
481         y = this->data + this->y_offset;
482         u = this->data + this->u_offset;
483         v = this->data + this->v_offset;
484 }
485
486 int VFrame::allocate_data(unsigned char *data, int shmid,
487                 long y_offset, long u_offset, long v_offset, int w, int h,
488                 int color_model, long bytes_per_line)
489 {
490         this->w = w;
491         this->h = h;
492         this->color_model = color_model;
493         this->bytes_per_pixel = calculate_bytes_per_pixel(color_model);
494         this->y_offset = this->u_offset = this->v_offset = 0;
495 //      if(shmid == 0) {
496 //              printf("VFrame::allocate_data %d shmid == 0\n", __LINE__, shmid);
497 //      }
498
499         this->bytes_per_line = bytes_per_line >= 0 ?
500                 bytes_per_line : this->bytes_per_pixel * w;
501
502 // Allocate data + padding for MMX
503         if(data) {
504 //printf("VFrame::allocate_data %d %p\n", __LINE__, this->data);
505                 memory_type = VFrame::SHARED;
506                 this->data = data;
507                 this->shmid = -1;
508                 this->y_offset = y_offset;
509                 this->u_offset = u_offset;
510                 this->v_offset = v_offset;
511         }
512         else if(shmid >= 0) {
513                 memory_type = VFrame::SHMGET;
514                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
515 //printf("VFrame::allocate_data %d shmid=%d data=%p\n", __LINE__, shmid, this->data);
516                 this->shmid = shmid;
517                 this->y_offset = y_offset;
518                 this->u_offset = u_offset;
519                 this->v_offset = v_offset;
520         }
521         else {
522                 memory_type = VFrame::PRIVATE;
523                 this->data = 0;
524                 int size = calculate_data_size(this->w, this->h,
525                         this->bytes_per_line, this->color_model);
526                 if( use_shm && size >= SHM_MIN_SIZE &&
527                     BC_WindowBase::get_resources()->use_vframe_shm() ) {
528                         this->shmid = shmget(IPC_PRIVATE, size, IPC_CREAT | 0777);
529                         if( this->shmid >= 0 ) {
530                                 this->data = (unsigned char*)shmat(this->shmid, NULL, 0);
531 //printf("VFrame::allocate_data %d %d %d %p\n", __LINE__, size, this->shmid, this->data);
532 // This causes it to automatically delete when the program exits.
533                                 shmctl(this->shmid, IPC_RMID, 0);
534                         }
535                         else {
536                                 printf("VFrame::allocate_data %d could not allocate"
537                                         " shared memory, %dx%d (model %d) size=0x%08x\n",
538                                         __LINE__, w, h, color_model, size);
539                                 BC_Trace::dump_shm_stats(stdout);
540                         }
541                 }
542 // Have to use malloc for libpng
543                 if( !this->data ) {
544                         this->data = (unsigned char *)malloc(size);
545                         this->shmid = -1;
546                 }
547 // Memory check
548 // if(this->w * this->h > 1500 * 1100)
549 // printf("VFrame::allocate_data 2 this=%p w=%d h=%d this->data=%p\n",
550 // this, this->w, this->h, this->data);
551
552                 if(!this->data)
553                         printf("VFrame::allocate_data %dx%d: memory exhausted.\n", this->w, this->h);
554 #ifdef LEAKER
555 printf("==new %p from %p sz %d\n", this->data, __builtin_return_address(0), size);
556 #endif
557
558 //printf("VFrame::allocate_data %d %p data=%p %d %d\n", __LINE__, this, this->data, this->w, this->h);
559 //if(size > 1000000) printf("VFrame::allocate_data %d\n", size);
560         }
561
562 // Create row pointers
563         create_row_pointers();
564         return 0;
565 }
566
567 void VFrame::set_memory(unsigned char *data,
568         int shmid,
569         long y_offset,
570         long u_offset,
571         long v_offset)
572 {
573         clear_objects(0);
574
575         if(data)
576         {
577                 memory_type = VFrame::SHARED;
578                 this->data = data;
579                 this->shmid = -1;
580                 this->y_offset = y_offset;
581                 this->u_offset = u_offset;
582                 this->v_offset = v_offset;
583         }
584         else
585         if(shmid >= 0)
586         {
587                 memory_type = VFrame::SHMGET;
588                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
589                 this->shmid = shmid;
590         }
591
592         y = this->data + this->y_offset;
593         u = this->data + this->u_offset;
594         v = this->data + this->v_offset;
595
596         create_row_pointers();
597 }
598
599 void VFrame::set_memory(BC_Bitmap *bitmap)
600 {
601         int shmid = 0;
602         unsigned char *data = 0;
603         if( bitmap->is_shared() && !bitmap->is_zombie() )
604                 shmid = bitmap->get_shmid();
605         else
606                 data = bitmap->get_data();
607         set_memory(data, shmid,
608                 bitmap->get_y_offset(),
609                 bitmap->get_u_offset(),
610                 bitmap->get_v_offset());
611 }
612
613 void VFrame::set_compressed_memory(unsigned char *data,
614         int shmid,
615         int data_size,
616         int data_allocated)
617 {
618         clear_objects(0);
619
620         if(data)
621         {
622                 memory_type = VFrame::SHARED;
623                 this->data = data;
624                 this->shmid = -1;
625         }
626         else
627         if(shmid >= 0)
628         {
629                 memory_type = VFrame::SHMGET;
630                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
631                 this->shmid = shmid;
632         }
633
634         this->compressed_allocated = data_allocated;
635         this->compressed_size = data_size;
636 }
637
638
639 // Reallocate uncompressed buffer with or without alpha
640 int VFrame::reallocate(
641         unsigned char *data,
642         int shmid,
643         long y_offset,
644         long u_offset,
645         long v_offset,
646         int w,
647         int h,
648         int color_model,
649         long bytes_per_line)
650 {
651 //      if(shmid == 0) printf("VFrame::reallocate %d shmid=%d\n", __LINE__, shmid);
652         clear_objects(0);
653 //      reset_parameters(0);
654         allocate_data(data,
655                 shmid,
656                 y_offset,
657                 u_offset,
658                 v_offset,
659                 w,
660                 h,
661                 color_model,
662                 bytes_per_line);
663         return 0;
664 }
665
666 int VFrame::allocate_compressed_data(long bytes)
667 {
668         if(bytes < 1) return 1;
669
670 // Want to preserve original contents
671         if(data && compressed_allocated < bytes)
672         {
673                 int new_shmid = -1;
674                 unsigned char *new_data = 0;
675                 if(BC_WindowBase::get_resources()->use_vframe_shm() && use_shm)
676                 {
677                         new_shmid = shmget(IPC_PRIVATE,
678                                 bytes,
679                                 IPC_CREAT | 0777);
680                         new_data = (unsigned char*)shmat(new_shmid, NULL, 0);
681                         shmctl(new_shmid, IPC_RMID, 0);
682                 }
683                 else
684                 {
685 // Have to use malloc for libpng
686                         new_data = (unsigned char *)malloc(bytes);
687                 }
688
689                 bcopy(data, new_data, compressed_allocated);
690 UNBUFFER(data);
691
692                 if(memory_type == VFrame::PRIVATE)
693                 {
694                         if(shmid > 0) {
695                                 if(data)
696                                         shmdt(data);
697                         }
698                         else
699                                 free(data);
700                 }
701                 else
702                 if(memory_type == VFrame::SHMGET)
703                 {
704                         if(data)
705                                 shmdt(data);
706                 }
707
708                 data = new_data;
709                 shmid = new_shmid;
710                 compressed_allocated = bytes;
711         }
712         else
713         if(!data)
714         {
715                 if(BC_WindowBase::get_resources()->use_vframe_shm() && use_shm)
716                 {
717                         shmid = shmget(IPC_PRIVATE,
718                                 bytes,
719                                 IPC_CREAT | 0777);
720                         data = (unsigned char*)shmat(shmid, NULL, 0);
721                         shmctl(shmid, IPC_RMID, 0);
722                 }
723                 else
724                 {
725 // Have to use malloc for libpng
726                         data = (unsigned char *)malloc(bytes);
727                 }
728
729                 compressed_allocated = bytes;
730                 compressed_size = 0;
731         }
732
733         return 0;
734 }
735
736 int VFramePng::read_png(const unsigned char *data, long sz, double xscale, double yscale)
737 {
738 // Test for RAW format
739         if(data[0] == 'R' && data[1] == 'A' && data[2] == 'W' && data[3] == ' ') {
740                 int new_color_model = BC_RGBA8888;
741                 w = data[4] | (data[5] << 8) | (data[6]  << 16) | (data[7]  << 24);
742                 h = data[8] | (data[9] << 8) | (data[10] << 16) | (data[11] << 24);
743                 int components = data[12];
744                 new_color_model = components == 3 ? BC_RGB888 : BC_RGBA8888;
745 // This shares the data directly
746 //              reallocate(data + 20, 0, 0, 0, w, h, new_color_model, -1);
747
748 // Can't use shared data for theme since button constructions overlay the
749 // images directly.
750                 reallocate(NULL, -1, 0, 0, 0, w, h, new_color_model, -1);
751                 memcpy(get_data(), data + 16, w * h * components);
752
753         }
754         else if(data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G') {
755                 int have_alpha = 0;
756                 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
757                 png_infop info_ptr = png_create_info_struct(png_ptr);
758                 int new_color_model;
759
760                 image_offset = 0;
761                 image = data;  image_size = sz;
762                 png_set_read_fn(png_ptr, this, PngReadFunction::png_read_function);
763                 png_read_info(png_ptr, info_ptr);
764
765                 w = png_get_image_width(png_ptr, info_ptr);
766                 h = png_get_image_height(png_ptr, info_ptr);
767
768                 int src_color_model = png_get_color_type(png_ptr, info_ptr);
769
770                 /* tell libpng to strip 16 bit/color files down to 8 bits/color */
771                 png_set_strip_16(png_ptr);
772
773                 /* extract multiple pixels with bit depths of 1, 2, and 4 from a single
774                  * byte into separate bytes (useful for paletted and grayscale images).
775                  */
776                 png_set_packing(png_ptr);
777
778                 /* expand paletted colors into true RGB triplets */
779                 if (src_color_model == PNG_COLOR_TYPE_PALETTE)
780                         png_set_expand(png_ptr);
781
782                 /* expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel */
783                 if (src_color_model == PNG_COLOR_TYPE_GRAY && png_get_bit_depth(png_ptr, info_ptr) < 8)
784                         png_set_expand(png_ptr);
785
786                 if (src_color_model == PNG_COLOR_TYPE_GRAY ||
787                     src_color_model == PNG_COLOR_TYPE_GRAY_ALPHA)
788                         png_set_gray_to_rgb(png_ptr);
789
790                 /* expand paletted or RGB images with transparency to full alpha channels
791                  * so the data will be available as RGBA quartets */
792                 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)){
793                         have_alpha = 1;
794                         png_set_expand(png_ptr);
795                 }
796
797                 switch(src_color_model)
798                 {
799                         case PNG_COLOR_TYPE_GRAY:
800                         case PNG_COLOR_TYPE_RGB:
801                                 new_color_model = BC_RGB888;
802                                 break;
803
804                         case PNG_COLOR_TYPE_GRAY_ALPHA:
805                         case PNG_COLOR_TYPE_RGB_ALPHA:
806                         default:
807                                 new_color_model = BC_RGBA8888;
808                                 break;
809
810                         case PNG_COLOR_TYPE_PALETTE:
811                                 if(have_alpha)
812                                         new_color_model = BC_RGBA8888;
813                                 else
814                                         new_color_model = BC_RGB888;
815                 }
816
817                 reallocate(NULL, -1, 0, 0, 0, w, h, new_color_model, -1);
818
819 //printf("VFrame::read_png %d %d %d %p\n", __LINE__, w, h, get_rows());
820                 png_read_image(png_ptr, get_rows());
821                 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
822         }
823         else {
824                 printf("VFrame::read_png %d: unknown file format"
825                         " 0x%02x 0x%02x 0x%02x 0x%02x\n",
826                         __LINE__, data[4], data[5], data[6], data[7]);
827                 return 1;
828         }
829         int ww = w * xscale, hh = h * yscale;
830         if( ww != w || hh != h ) {
831                 VFrame vframe(*this);
832                 reallocate(NULL, -1, 0, 0, 0, ww, hh, color_model, -1);
833                 transfer_from(&vframe);
834         }
835         return 0;
836 }
837
838 int VFrame::write_png(const char *path)
839 {
840         VFrame *vframe = this;
841         png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
842         png_infop info_ptr = png_create_info_struct(png_ptr);
843         FILE *out_fd = fopen(path, "w");
844         if(!out_fd) {
845                 printf("VFrame::write_png %d %s %s\n", __LINE__, path, strerror(errno));
846                 return 1;
847         }
848
849         int png_cmodel = PNG_COLOR_TYPE_RGB;
850         int bc_cmodel = get_color_model();
851         switch( bc_cmodel ) {
852         case BC_RGB888:                                          break;
853         case BC_RGBA8888: png_cmodel = PNG_COLOR_TYPE_RGB_ALPHA; break;
854         case BC_A8:       png_cmodel = PNG_COLOR_TYPE_GRAY;      break;
855         default:
856                 bc_cmodel = BC_RGB888;
857                 if( BC_CModels::has_alpha(bc_cmodel) ) {
858                         bc_cmodel = BC_RGBA8888;
859                         png_cmodel = PNG_COLOR_TYPE_RGB_ALPHA;
860                 }
861                 vframe = new VFrame(get_w(), get_h(), bc_cmodel, 0);
862                 vframe->transfer_from(this);
863                 break;
864         }
865         png_init_io(png_ptr, out_fd);
866         png_set_compression_level(png_ptr, 9);
867         png_set_IHDR(png_ptr, info_ptr, get_w(), get_h(), 8, png_cmodel,
868                 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
869         png_write_info(png_ptr, info_ptr);
870         png_write_image(png_ptr, vframe->get_rows());
871         png_write_end(png_ptr, info_ptr);
872         png_destroy_write_struct(&png_ptr, &info_ptr);
873         fclose(out_fd);
874         if( vframe != this ) delete vframe;
875         return 0;
876 }
877
878 void VFrame::write_ppm(VFrame *vfrm, const char *fmt, ...)
879 {
880         va_list ap;
881         va_start(ap, fmt);
882         char fn[BCTEXTLEN];
883         vsnprintf(fn, sizeof(fn), fmt, ap);
884         va_end(ap);
885         FILE *fp = fopen(fn,"w");
886         if( !fp ) { perror("write_ppm"); return; }
887         VFrame *frm = vfrm;
888         if( frm->get_color_model() != BC_RGB888 ) {
889                 frm = new VFrame(frm->get_w(), frm->get_h(), BC_RGB888);
890                 frm->transfer_from(vfrm);
891         }
892         int w = frm->get_w(), h = frm->get_h();
893         fprintf(fp,"P6\n%d %d\n255\n",w,h);
894         unsigned char **rows = frm->get_rows();
895         for( int i=0; i<h; ++i ) fwrite(rows[i],3,w,fp);
896         fclose(fp);
897         if( frm != vfrm ) delete frm;
898 }
899
900
901 #define ZERO_YUV(components, type, max) \
902 { \
903         for(int i = 0; i < h; i++) \
904         { \
905                 type *row = (type*)get_rows()[i]; \
906                 for(int j = 0; j < w; j++) \
907                 { \
908                         row[j * components] = 0; \
909                         row[j * components + 1] = (max + 1) / 2; \
910                         row[j * components + 2] = (max + 1) / 2; \
911                         if(components == 4) row[j * components + 3] = 0; \
912                 } \
913         } \
914 }
915
916 int VFrame::clear_frame()
917 {
918         int sz = w * h;
919 //printf("VFrame::clear_frame %d\n", __LINE__);
920         switch(color_model) {
921         case BC_COMPRESSED:
922                 break;
923
924         case BC_YUV410P:
925                 bzero(get_y(), sz);
926                 memset(get_u(), 0x80, w / 4 * h / 4);
927                 memset(get_v(), 0x80, w / 4 * h / 4);
928                 break;
929
930         case BC_YUV411P:
931         case BC_YUV420P:
932         case BC_YUV420PI:
933                 bzero(get_y(), sz);
934                 memset(get_u(), 0x80, sz / 4);
935                 memset(get_v(), 0x80, sz / 4);
936                 break;
937
938         case BC_YUV422P:
939                 bzero(get_y(), sz);
940                 memset(get_u(), 0x80, sz / 2);
941                 memset(get_v(), 0x80, sz / 2);
942                 break;
943
944         case BC_GBRP:
945                 bzero(get_y(), sz);
946                 bzero(get_u(), sz);
947                 bzero(get_b(), sz);
948                 break;
949
950         case BC_RGBA_FLOATP: if( a ) {
951                 float *ap = (float *)a;
952                 for( int i=sz; --i>=0; ++ap ) *ap = 0.f; }
953         case BC_RGB_FLOATP: {
954                 float *rp = (float *)y;
955                 for( int i=sz; --i>=0; ++rp ) *rp = 0.f;
956                 float *gp = (float *)u;
957                 for( int i=sz; --i>=0; ++gp ) *gp = 0.f;
958                 float *bp = (float *)v;
959                 for( int i=sz; --i>=0; ++bp ) *bp = 0.f;
960                 break; }
961         case BC_YUV444P:
962                 bzero(get_y(), sz);
963                 memset(get_u(), 0x80, sz);
964                 memset(get_v(), 0x80, sz);
965                 break;
966
967         case BC_YUV888:
968                 ZERO_YUV(3, unsigned char, 0xff);
969                 break;
970
971         case BC_YUVA8888:
972                 ZERO_YUV(4, unsigned char, 0xff);
973                 break;
974
975         case BC_YUV161616:
976                 ZERO_YUV(3, uint16_t, 0xffff);
977                 break;
978
979         case BC_YUVA16161616:
980                 ZERO_YUV(4, uint16_t, 0xffff);
981                 break;
982
983         default:
984                 bzero(data, calculate_data_size(w, h, bytes_per_line, color_model));
985                 break;
986         }
987         return 0;
988 }
989
990 void VFrame::rotate90()
991 {
992 // Allocate new frame
993         int new_w = h, new_h = w;
994         VFrame new_frame(new_w, new_h, color_model);
995         unsigned char **new_rows = new_frame.get_rows();
996 // Copy data
997         for(int in_y = 0, out_x = new_w - 1; in_y < h; in_y++, out_x--)
998         {
999                 for(int in_x = 0, out_y = 0; in_x < w; in_x++, out_y++)
1000                 {
1001                         for(int k = 0; k < bytes_per_pixel; k++)
1002                         {
1003                                 new_rows[out_y][out_x * bytes_per_pixel + k] =
1004                                         rows[in_y][in_x * bytes_per_pixel + k];
1005                         }
1006                 }
1007         }
1008
1009 // Swap frames
1010 // swap memory
1011         unsigned char *new_data = new_frame.data;
1012         new_frame.data = data;
1013         data = new_data;
1014 // swap rows
1015         new_rows = new_frame.rows;
1016         new_frame.rows = rows;
1017         rows = new_rows;
1018 // swap shmid
1019         int new_shmid = new_frame.shmid;
1020         new_frame.shmid = shmid;
1021         shmid = new_shmid;
1022 // swap bytes_per_line
1023         int new_bpl = new_frame.bytes_per_line;
1024         new_frame.bytes_per_line = bytes_per_line;
1025         bytes_per_line = new_bpl;
1026         new_frame.clear_objects(0);
1027
1028         w = new_frame.w;
1029         h = new_frame.h;
1030 }
1031
1032 void VFrame::rotate270()
1033 {
1034 // Allocate new frame
1035         int new_w = h, new_h = w;
1036         VFrame new_frame(new_w, new_h, color_model);
1037         unsigned char **new_rows = new_frame.get_rows();
1038 // Copy data
1039         for(int in_y = 0, out_x = 0; in_y < h; in_y++, out_x++)
1040         {
1041                 for(int in_x = 0, out_y = new_h - 1; in_x < w; in_x++, out_y--)
1042                 {
1043                         for(int k = 0; k < bytes_per_pixel; k++)
1044                         {
1045                                 new_rows[out_y][out_x * bytes_per_pixel + k] =
1046                                         rows[in_y][in_x * bytes_per_pixel + k];
1047                         }
1048                 }
1049         }
1050
1051 // Swap frames
1052 // swap memory
1053         unsigned char *new_data = new_frame.data;
1054         new_frame.data = data;
1055         data = new_data;
1056 // swap rows
1057         new_rows = new_frame.rows;
1058         new_frame.rows = rows;
1059         rows = new_rows;
1060 // swap shmid
1061         int new_shmid = new_frame.shmid;
1062         new_frame.shmid = shmid;
1063         shmid = new_shmid;
1064 // swap bytes_per_line
1065         int new_bpl = new_frame.bytes_per_line;
1066         new_frame.bytes_per_line = bytes_per_line;
1067         bytes_per_line = new_bpl;
1068         new_frame.clear_objects(0);
1069
1070         w = new_frame.w;
1071         h = new_frame.h;
1072 }
1073
1074 void VFrame::flip_vert()
1075 {
1076         unsigned char temp[bytes_per_line];
1077         for( int i=0, j=h; --j>i; ++i ) {
1078                 memcpy(temp, rows[j], bytes_per_line);
1079                 memcpy(rows[j], rows[i], bytes_per_line);
1080                 memcpy(rows[i], temp, bytes_per_line);
1081         }
1082 }
1083
1084 void VFrame::flip_horiz()
1085 {
1086         unsigned char temp[32];
1087         for(int i = 0; i < h; i++)
1088         {
1089                 unsigned char *row = rows[i];
1090                 for(int j = 0; j < bytes_per_line / 2; j += bytes_per_pixel)
1091                 {
1092                         memcpy(temp, row + j, bytes_per_pixel);
1093                         memcpy(row + j, row + bytes_per_line - j - bytes_per_pixel, bytes_per_pixel);
1094                         memcpy(row + bytes_per_line - j - bytes_per_pixel, temp, bytes_per_pixel);
1095                 }
1096         }
1097 }
1098
1099
1100
1101 int VFrame::copy_from(VFrame *frame)
1102 {
1103         if(this->w != frame->get_w() ||
1104                 this->h != frame->get_h())
1105         {
1106                 printf("VFrame::copy_from %d sizes differ src %dx%d != dst %dx%d\n",
1107                         __LINE__,
1108                         frame->get_w(),
1109                         frame->get_h(),
1110                         get_w(),
1111                         get_h());
1112                 return 1;
1113         }
1114
1115         int w = MIN(this->w, frame->get_w());
1116         int h = MIN(this->h, frame->get_h());
1117         timestamp = frame->timestamp;
1118
1119         switch(frame->color_model)
1120         {
1121                 case BC_COMPRESSED:
1122                         allocate_compressed_data(frame->compressed_size);
1123                         memcpy(data, frame->data, frame->compressed_size);
1124                         this->compressed_size = frame->compressed_size;
1125                         break;
1126
1127                 case BC_YUV410P:
1128                         memcpy(get_y(), frame->get_y(), w * h);
1129                         memcpy(get_u(), frame->get_u(), w / 4 * h / 4);
1130                         memcpy(get_v(), frame->get_v(), w / 4 * h / 4);
1131                         break;
1132
1133                 case BC_YUV420P:
1134                 case BC_YUV420PI:
1135                 case BC_YUV411P:
1136 //printf("%d %d %p %p %p %p %p %p\n", w, h, get_y(), get_u(), get_v(), frame->get_y(), frame->get_u(), frame->get_v());
1137                         memcpy(get_y(), frame->get_y(), w * h);
1138                         memcpy(get_u(), frame->get_u(), w * h / 4);
1139                         memcpy(get_v(), frame->get_v(), w * h / 4);
1140                         break;
1141
1142                 case BC_YUV422P:
1143 //printf("%d %d %p %p %p %p %p %p\n", w, h, get_y(), get_u(), get_v(), frame->get_y(), frame->get_u(), frame->get_v());
1144                         memcpy(get_y(), frame->get_y(), w * h);
1145                         memcpy(get_u(), frame->get_u(), w * h / 2);
1146                         memcpy(get_v(), frame->get_v(), w * h / 2);
1147                         break;
1148
1149                 case BC_YUV444P:
1150 //printf("%d %d %p %p %p %p %p %p\n", w, h, get_y(), get_u(), get_v(), frame->get_y(), frame->get_u(), frame->get_v());
1151                         memcpy(get_y(), frame->get_y(), w * h);
1152                         memcpy(get_u(), frame->get_u(), w * h);
1153                         memcpy(get_v(), frame->get_v(), w * h);
1154                         break;
1155                 default:
1156 // printf("VFrame::copy_from %d\n", calculate_data_size(w,
1157 //                              h,
1158 //                              -1,
1159 //                              frame->color_model));
1160 // Copy without extra 4 bytes in case the source is a hardware device
1161                         memmove(data, frame->data, get_data_size());
1162                         break;
1163         }
1164
1165         return 0;
1166 }
1167
1168 int VFrame::transfer_from(VFrame *that, int bg_color, int in_x, int in_y, int in_w, int in_h)
1169 {
1170         timestamp = that->timestamp;
1171         copy_params(that);
1172
1173         if( in_x == 0 && in_y == 0 && in_w == that->get_w() && in_h == that->get_h() &&
1174             bg_color == 0 && this->get_color_model() == that->get_color_model() &&
1175             this->get_w() == that->get_w() && this->get_h() == that->get_h() &&
1176             this->get_bytes_per_line() == that->get_bytes_per_line() )
1177                 return this->copy_from(that);
1178
1179 #if 0
1180         BC_CModels::transfer(
1181                 this->get_rows(), that->get_rows(),          // Packed data out/in
1182                 this->get_y(), this->get_u(), this->get_v(), // Planar data out/in
1183                 that->get_y(), that->get_u(), that->get_v(),
1184                 0, 0, that->get_w(), that->get_h(),          // Dimensions in/out
1185                 0, 0, this->get_w(), this->get_h(),
1186                 that->get_color_model(), this->get_color_model(), // Color models in/out
1187                 bg_color,                                    // alpha blend bg_color
1188                 that->get_bytes_per_line(),
1189                 this->get_bytes_per_line());                 // rowspans (of luma for YUV)
1190 #else
1191         unsigned char *in_ptrs[4], *out_ptrs[4];
1192         unsigned char **inp, **outp;
1193         if( BC_CModels::is_planar(that->get_color_model()) ) {
1194                 in_ptrs[0] = that->get_y();
1195                 in_ptrs[1] = that->get_u();
1196                 in_ptrs[2] = that->get_v();
1197                 in_ptrs[3] = that->get_a();
1198                 inp = in_ptrs;
1199         }
1200         else
1201                 inp = that->get_rows();
1202         if( BC_CModels::is_planar(this->get_color_model()) ) {
1203                 out_ptrs[0] = this->get_y();
1204                 out_ptrs[1] = this->get_u();
1205                 out_ptrs[2] = this->get_v();
1206                 out_ptrs[3] = this->get_a();
1207                 outp = out_ptrs;
1208         }
1209         else
1210                 outp = this->get_rows();
1211         BC_CModels::transfer(outp, this->get_color_model(),
1212                         0, 0, this->get_w(), this->get_h(),
1213                         this->get_bytes_per_line(),
1214                 inp, that->get_color_model(),
1215                         in_x, in_y, in_w, in_h,
1216                         that->get_bytes_per_line(),
1217                 bg_color);
1218 #endif
1219         return 0;
1220 }
1221
1222
1223 int VFrame::get_scale_tables(int *column_table, int *row_table,
1224                         int in_x1, int in_y1, int in_x2, int in_y2,
1225                         int out_x1, int out_y1, int out_x2, int out_y2)
1226 {
1227         int i;
1228         float w_in = in_x2 - in_x1;
1229         float h_in = in_y2 - in_y1;
1230         int w_out = out_x2 - out_x1;
1231         int h_out = out_y2 - out_y1;
1232
1233         float hscale = w_in / w_out;
1234         float vscale = h_in / h_out;
1235
1236         for(i = 0; i < w_out; i++)
1237         {
1238                 column_table[i] = (int)(hscale * i);
1239         }
1240
1241         for(i = 0; i < h_out; i++)
1242         {
1243                 row_table[i] = (int)(vscale * i) + in_y1;
1244         }
1245         return 0;
1246 }
1247
1248 void VFrame::push_prev_effect(const char *name)
1249 {
1250         char *ptr;
1251         prev_effects.append(ptr = new char[strlen(name) + 1]);
1252         strcpy(ptr, name);
1253         if(prev_effects.total > MAX_STACK_ELEMENTS) prev_effects.remove_object(0);
1254 }
1255
1256 void VFrame::pop_prev_effect()
1257 {
1258         if(prev_effects.total)
1259                 prev_effects.remove_object(prev_effects.last());
1260 }
1261
1262 void VFrame::push_next_effect(const char *name)
1263 {
1264         char *ptr;
1265         next_effects.append(ptr = new char[strlen(name) + 1]);
1266         strcpy(ptr, name);
1267         if(next_effects.total > MAX_STACK_ELEMENTS) next_effects.remove_object(0);
1268 }
1269
1270 void VFrame::pop_next_effect()
1271 {
1272         if(next_effects.total)
1273                 next_effects.remove_object(next_effects.last());
1274 }
1275
1276 const char* VFrame::get_next_effect(int number)
1277 {
1278         if(!next_effects.total) return "";
1279         else
1280         if(number > next_effects.total - 1) number = next_effects.total - 1;
1281
1282         return next_effects.values[next_effects.total - number - 1];
1283 }
1284
1285 const char* VFrame::get_prev_effect(int number)
1286 {
1287         if(!prev_effects.total) return "";
1288         else
1289         if(number > prev_effects.total - 1) number = prev_effects.total - 1;
1290
1291         return prev_effects.values[prev_effects.total - number - 1];
1292 }
1293
1294 BC_Hash* VFrame::get_params()
1295 {
1296         return params;
1297 }
1298
1299 void VFrame::clear_stacks()
1300 {
1301         next_effects.remove_all_objects();
1302         prev_effects.remove_all_objects();
1303         params->clear();
1304         status = 1;
1305 }
1306
1307 void VFrame::copy_params(VFrame *src)
1308 {
1309         status = src->status;
1310         params->copy_from(src->params);
1311 }
1312
1313 void VFrame::copy_stacks(VFrame *src)
1314 {
1315         clear_stacks();
1316
1317         for( int i=0; i < src->next_effects.total; ++i )
1318                 next_effects.append(cstrdup(src->next_effects[i]));
1319         for( int i=0; i < src->prev_effects.total; ++i )
1320                 prev_effects.append(cstrdup(src->prev_effects[i]));
1321
1322         copy_params(src);
1323 }
1324
1325 int VFrame::copy_vframe(VFrame *frame)
1326 {
1327         copy_stacks(frame);
1328         return copy_from(frame);
1329 }
1330
1331 int VFrame::equal_stacks(VFrame *src)
1332 {
1333         for(int i = 0; i < src->next_effects.total && i < next_effects.total; i++)
1334         {
1335                 if(strcmp(src->next_effects.values[i], next_effects.values[i])) return 0;
1336         }
1337
1338         for(int i = 0; i < src->prev_effects.total && i < prev_effects.total; i++)
1339         {
1340                 if(strcmp(src->prev_effects.values[i], prev_effects.values[i])) return 0;
1341         }
1342
1343         if(!params->equivalent(src->params)) return 0;
1344         return 1;
1345 }
1346
1347 void VFrame::dump_stacks()
1348 {
1349         printf("VFrame::dump_stacks\n");
1350         printf("        next_effects:\n");
1351         for(int i = next_effects.total - 1; i >= 0; i--)
1352                 printf("                %s\n", next_effects.values[i]);
1353         printf("        prev_effects:\n");
1354         for(int i = prev_effects.total - 1; i >= 0; i--)
1355                 printf("                %s\n", prev_effects.values[i]);
1356 }
1357
1358 void VFrame::dump_params()
1359 {
1360         params->dump();
1361 }
1362
1363 void VFrame::dump()
1364 {
1365         printf("VFrame::dump %d this=%p\n", __LINE__, this);
1366         printf("    w=%d h=%d colormodel=%d rows=%p use_shm=%d shmid=%d\n",
1367                 w, h, color_model, rows, use_shm, shmid);
1368 }
1369
1370
1371 int VFrame::get_memory_usage()
1372 {
1373         if(get_compressed_allocated()) return get_compressed_allocated();
1374         return get_h() * get_bytes_per_line();
1375 }
1376
1377 // rgb component colors (eg. from colors.h)
1378 // a (~alpha) transparency, 0x00==solid .. 0xff==transparent
1379 void VFrame::set_pixel_color(int rgb, int a)
1380 {
1381         pixel_rgb = (rgb&0xffffff) | ~a<<24;
1382         int ir = 0xff & (pixel_rgb >> 16);
1383         int ig = 0xff & (pixel_rgb >> 8);
1384         int ib = 0xff & (pixel_rgb >> 0);
1385         YUV::yuv.rgb_to_yuv_8(ir, ig, ib);
1386         pixel_yuv =  (~a<<24) | (ir<<16) | (ig<<8) | (ib<<0);
1387 }
1388
1389 void VFrame::set_stiple(int mask)
1390 {
1391         stipple = mask;
1392 }
1393
1394 int VFrame::draw_pixel(int x, int y)
1395 {
1396         if( x < 0 || y < 0 || x >= get_w() || y >= get_h() ) return 1;
1397
1398 #define DRAW_PIXEL(type, r, g, b, comps, a) { \
1399         type **rows = (type**)get_rows(); \
1400         type *rp = rows[y], *bp = rp + x*comps; \
1401         bp[0] = r; \
1402         if( comps > 1 ) { bp[1] = g; bp[2] = b; } \
1403         if( comps == 4 )  bp[3] = a; \
1404 }
1405         float fr = 0, fg = 0, fb = 0, fa = 0;
1406         int pixel_color = BC_CModels::is_yuv(color_model) ? pixel_yuv : pixel_rgb;
1407         int ir = (0xff & (pixel_color >> 16));
1408         int ig = (0xff & (pixel_color >> 8));
1409         int ib = (0xff & (pixel_color >> 0));
1410         int ia = (0xff & (pixel_color >> 24)) ^ 0xff;  // transparency, not opacity
1411         if( (x+y) & stipple ) {
1412                 ir = 255 - ir;  ig = 255 - ig;  ib = 255 - ib;
1413         }
1414         int rr = (ir<<8) | ir, gg = (ig<<8) | ig, bb = (ib<<8) | ib, aa = (ia<<8) | ia;
1415         if( BC_CModels::is_float(color_model) ) {
1416                 fr = rr/65535.f;  fg = gg/65535.f;  fb = bb/65535.f;  fa = aa/65535.f;
1417         }
1418
1419         switch(get_color_model()) {
1420         case BC_A8:
1421                 DRAW_PIXEL(uint8_t, ib, 0, 0, 1, 0);
1422                 break;
1423         case BC_RGB888:
1424         case BC_YUV888:
1425                 DRAW_PIXEL(uint8_t, ir, ig, ib, 3, 0);
1426                 break;
1427         case BC_RGBA8888:
1428         case BC_YUVA8888:
1429                 DRAW_PIXEL(uint8_t, ir, ig, ib, 4, ia);
1430                 break;
1431         case BC_RGB161616:
1432         case BC_YUV161616:
1433                 DRAW_PIXEL(uint16_t, rr, gg, bb, 3, 0);
1434                 break;
1435         case BC_RGBA16161616:
1436         case BC_YUVA16161616:
1437                 DRAW_PIXEL(uint16_t, rr, gg, bb, 4, aa);
1438                 break;
1439         case BC_RGB_FLOAT:
1440                 DRAW_PIXEL(float, fr, fg, fb, 3, 0);
1441                 break;
1442         case BC_RGBA_FLOAT:
1443                 DRAW_PIXEL(float, fr, fg, fb, 4, fa);
1444                 break;
1445         }
1446         return 0;
1447 }
1448
1449
1450 // Bresenham's
1451 void VFrame::draw_line(int x1, int y1, int x2, int y2)
1452 {
1453         if( y1 > y2 ) {
1454                 int tx = x1;  x1 = x2;  x2 = tx;
1455                 int ty = y1;  y1 = y2;  y2 = ty;
1456         }
1457
1458         int x = x1, y = y1;
1459         int dx = x2-x1, dy = y2-y1;
1460         int dx2 = 2*dx, dy2 = 2*dy;
1461         if( dx < 0 ) dx = -dx;
1462         int r = dx > dy ? dx : dy, n = r;
1463         int dir = 0;
1464         if( dx2 < 0 ) dir += 1;
1465         if( dy >= dx ) {
1466                 if( dx2 >= 0 ) do {     /* +Y, +X */
1467                         draw_pixel(x, y++);
1468                         if( (r -= dx2) < 0 ) { r += dy2;  ++x; }
1469                 } while( --n >= 0 );
1470                 else do {               /* +Y, -X */
1471                         draw_pixel(x, y++);
1472                         if( (r += dx2) < 0 ) { r += dy2;  --x; }
1473                 } while( --n >= 0 );
1474         }
1475         else {
1476                 if( dx2 >= 0 ) do {     /* +X, +Y */
1477                         draw_pixel(x++, y);
1478                         if( (r -= dy2) < 0 ) { r += dx2;  ++y; }
1479                 } while( --n >= 0 );
1480                 else do {               /* -X, +Y */
1481                         draw_pixel(x--, y);
1482                         if( (r -= dy2) < 0 ) { r -= dx2;  ++y; }
1483                 } while( --n >= 0 );
1484         }
1485 }
1486
1487 // g++ -dD -E - < /dev/null | grep DBL_EPSILON
1488 #ifndef __DBL_EPSILON__
1489 #define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
1490 #endif
1491 // weakest fraction * graphics integer range
1492 #define RND_EPSILON (__DBL_EPSILON__*65536)
1493
1494 class smooth_line {
1495         int rnd(double v) { return round(v)+RND_EPSILON; }
1496         VFrame *vframe;
1497 public:
1498         int sx, sy, ex, ey;     /* current point, end point */
1499         int xs, ys;             /* x/y quadrant sign -1/1 */
1500         int64_t A, B, C;        /* quadratic coefficients */
1501         int64_t r, dx, dy;      /* residual, dr/dx and dr/dy */
1502         int xmxx, xmxy;         /* x,y at apex */
1503         int done;
1504
1505         void init0(int x1,int y1, int x2,int y2, int x3,int y3, int top);
1506         void init1(int x1,int y1, int x2,int y2, int x3,int y3);
1507         int64_t rx() { return r + xs*8*dx + 4*A; }
1508         void moveX(int64_t r) {
1509                 dx += xs*A;   dy -= xs*B;
1510                 this->r = r;  sx += xs;
1511         }
1512         int64_t ry() { return r + 8*dy + 4*C; }
1513         void moveY(int64_t r) {
1514                 dx -= B;      dy += C;
1515                 this->r = r;  ++sy;
1516         }
1517         void draw();
1518
1519         smooth_line(VFrame *vframe) { this->vframe = vframe; this->done = 0; }
1520 };
1521
1522
1523 void smooth_line::draw()
1524 {
1525         if( done ) return;
1526         if( abs(dy) >= abs(dx) ) {
1527                 if( xs*(sx-xmxx) >= 0 ) {
1528                         if( ys > 0 ) { done = 1;  return; }
1529                         if( dy < 0 || ry() < 0 ) { moveY(ry()); goto xit; }
1530                         xmxx = ex;  xmxy = ey;
1531                         ys = 1;  xs = -xs;
1532                 }
1533                 moveX(rx());
1534                 int64_t rr = ry();
1535                 if( abs(rr) < abs(r) )
1536                         moveY(rr);
1537         }
1538         else {
1539                 if( sy >= xmxy ) {
1540                         if( ys > 0 ) { done = 1;  return; }
1541                         xmxx = ex;  xmxy = ey;
1542                         ys = 1;  xs = -xs;
1543                 }
1544                 moveY(ry());
1545                 int64_t rr = rx();
1546                 if( abs(rr) < abs(r) )
1547                         moveX(rr);
1548         }
1549 xit:    vframe->draw_pixel(sx, sy);
1550 }
1551
1552 void VFrame::draw_smooth(int x1, int y1, int x2, int y2, int x3, int y3)
1553 {
1554         if( (x1 == x2 && y1 == y2) || (x2 == x3 && y2 == y3) )
1555                 draw_line(x1,y1, x3,y3);
1556         else if( x1 == x3 && y1 == y3 )
1557                 draw_line(x1,y1, x2,y2);
1558         else if( (x2-x1) * (y2-y3) == (x2-x3) * (y2-y1) ) {
1559                 // co-linear, draw line from min to max
1560                 if( x1 < x3 ) {
1561                         if( x2 < x1 ) { x1 = x2;  y1 = y2; }
1562                         if( x2 > x3 ) { x3 = x2;  y3 = y2; }
1563                 }
1564                 else {
1565                         if( x2 > x1 ) { x1 = x2;  y1 = y2; }
1566                         if( x2 < x3 ) { x3 = x2;  y3 = y2; }
1567                 }
1568                 draw_line(x1,y1, x3,y3);
1569         }
1570         else
1571                 smooth_draw(x1, y1, x2, y2, x3, y3);
1572 }
1573
1574 /*
1575   Non-Parametric Smooth Curve Generation. Don Kelly 1984
1576
1577      P+-----+Q'= virtual
1578      /     /       origin
1579     /     /
1580   Q+-----+R
1581
1582    Let the starting point be P. the ending point R. and the tangent vertex Q.
1583    A general point Z on the curve is then
1584         Z = (P + R - Q) + (Q - P) sin t + (Q - R) cos t
1585
1586    Expanding the Cartesian coordinates around (P + R - Q) gives
1587         [x y] = Z - (P + R - Q)
1588         [a c] = Q - P
1589         [b d] = Q - R
1590         x = a*sin(t) + b*cos(t)
1591         y = c*sin(t) + d*cos(t)
1592
1593    from which t can now be eliminated via
1594         c*x - a*y = (c*b - a*d)*cos(t)
1595         d*x - b*y = (a*d - c*b)*sin(t)
1596
1597    giving the Cartesian equation for the ellipse as
1598         f(x, y) = (c*x - a*y)**2 + (d*x - b*y)**2 - (a*d - c*b)**2 = 0
1599
1600    or:  f(x, y) = A*x**2 - 2*B*x*y + C*y**2 + B**2 - A*C = 0
1601    where: A = c**2 + d**2,  B = a*c + b*d,  C = a**2 + b**2
1602
1603    The maximum y extent of the ellipse may now be derived as follows:
1604         let df/dx = 0,  2*A*x = 2*B*y,  x = y*B/A
1605         f(x, y) == B**2 * y**2 / A - 2*B**2 * y**2 / A + C*y**2 + B**2 - A*C = 0
1606            (A*C - B**2)*y = (A*C - B**2)*A
1607            max x = sqrt(C), at y = B/sqrt(C)
1608            max y = sqrt(A), at x = B/sqrt(A)
1609
1610  */
1611
1612
1613 /* x1,y1 = P, x2,y2 = Q, x3,y3=R,
1614  *  draw from P to Q to R   if top=0
1615  *    or from P to (x,ymax) if top>0
1616  *    or from Q to (x,ymax) if top<0
1617  */
1618 void smooth_line::init0(int x1,int y1, int x2,int y2, int x3,int y3, int top)
1619 {
1620         int x0 = x1+x3-x2, y0 = y1+y3-y2; // Q'
1621
1622         int a = x2-x1,  c = y2-y1;
1623         int b = x2-x3,  d = y2-y3;
1624         A = c*c + d*d;  C = a*a + b*b;  B = a*c + b*d;
1625
1626         sx = top >= 0 ? x1 : x3;
1627         sy = top >= 0 ? y1 : y3;
1628         xs = x2 > sx || (x2==sx && (x1+x3-sx)>=x2) ? 1 : -1;
1629         int64_t px = sx-x0, py = sy-y0;
1630         dx = A*px - B*py;  dy = C*py - B*px;
1631         r = 0;
1632
1633         if( top ) {
1634                 double ymy = sqrt(A), ymx = B/ymy;
1635                 ex = x0 + rnd(ymx);
1636                 ey = y0 + rnd(ymy);
1637         }
1638         else {
1639                 ex = x3;  ey = y3;
1640         }
1641
1642         ys = a*b > 0 && (!top || top*xs*(b*c - a*d) > 0) ? -1 : 1;
1643         if( ys < 0 ) {
1644                 double xmx = xs*sqrt(C), xmy = B/xmx;
1645                 xmxx = x0 + rnd(xmx);
1646                 xmxy = y0 + rnd(xmy);
1647         }
1648         else {
1649                 xmxx = ex; xmxy = ey;
1650         }
1651 }
1652
1653 /*  x1,y1 = P, x2,y2 = Q, x3,y3=R,
1654  *  draw from (x,ymax) to P
1655  */
1656 void smooth_line::init1(int x1,int y1, int x2,int y2, int x3,int y3)
1657 {
1658         int x0 = x1+x3-x2, y0 = y1+y3-y2; // Q'
1659
1660         int a = x2-x1,  c = y2-y1;
1661         int b = x2-x3,  d = y2-y3;
1662         A = c*c + d*d;  C = a*a + b*b;  B = a*c + b*d;
1663
1664         double ymy = -sqrt(A), ymx = B/ymy;
1665         int64_t px = rnd(ymx), py = rnd(ymy);
1666         sx = x0 + px;  ex = x1;
1667         sy = y0 + py;  ey = y1;
1668         xs = x2 > x1 || (x2==x1 && x3>=x2) ? 1 : -1;
1669         dx = A*px - B*py;  dy = C*py - B*px;
1670         r = 4 * (A*px*px - 2*B*px*py + C*py*py + B*B - A*C);
1671
1672         ys = a*b > 0 && xs*(b*c - a*d) < 0 ? -1 : 1;
1673         if( ys < 0 ) {
1674                 double xmx = xs*sqrt(C), xmy = B/xmx;
1675                 xmxx = x0 + rnd(xmx);
1676                 xmxy = y0 + rnd(xmy);
1677         }
1678         else {
1679                 xs = -xs;
1680                 xmxx = ex; xmxy = ey;
1681         }
1682         if( xs > 0 )
1683                 vframe->draw_pixel(sx, sy);
1684         while( xs*(sx-xmxx) < 0 && (xs*dx < 0 || rx() < 0) ) {
1685                 moveX(rx());
1686                 vframe->draw_pixel(sx, sy);
1687         }
1688 }
1689
1690
1691 void VFrame::smooth_draw(int x1, int y1, int x2, int y2, int x3, int y3)
1692 {
1693 //printf("p smooth_draw( %d,%d, %d,%d, %d,%d )\n", x1,y1,x2,y2,x3,y3);
1694         if( y1 > y3 ) {         // make y3 >= y1
1695                 int xt = x1;  x1 = x3;  x3 = xt;
1696                 int yt = y1;  y1 = y3;  y3 = yt;
1697         }
1698         if( y1 > y2 && y3 > y2 ) {
1699                 smooth_line lt(this), rt(this); // Q on bottom
1700                 lt.init1(x1, y1, x2, y2, x3, y3);
1701                 rt.init1(x3, y3, x2, y2, x1, y1);
1702                 while( !lt.done || !rt.done ) {
1703                         lt.draw();
1704                         rt.draw();
1705                 }
1706         }
1707         else if( y1 < y2 && y3 < y2 ) {
1708                 smooth_line lt(this), rt(this); // Q on top
1709                 lt.init0(x1, y1, x2, y2, x3, y3, 1);
1710                 draw_pixel(lt.sx, lt.sy);
1711                 rt.init0(x1, y1, x2, y2, x3, y3, -1);
1712                 draw_pixel(rt.sx, rt.sy);
1713                 while( !lt.done || !rt.done ) {
1714                         lt.draw();
1715                         rt.draw();
1716                 }
1717         }
1718         else {
1719                 smooth_line pt(this);           // Q in between
1720                 pt.init0(x1, y1, x2, y2, x3, y3, 0);
1721                 draw_pixel(pt.sx, pt.sy);
1722                 while( !pt.done ) {
1723                         pt.draw();
1724                 }
1725         }
1726 }
1727
1728
1729 void VFrame::draw_rect(int x1, int y1, int x2, int y2)
1730 {
1731         draw_line(x1, y1, x2, y1);
1732         draw_line(x2, y1 + 1, x2, y2);
1733         draw_line(x2 - 1, y2, x1, y2);
1734         draw_line(x1, y2 - 1, x1, y1 + 1);
1735 }
1736
1737
1738 void VFrame::draw_oval(int x1, int y1, int x2, int y2)
1739 {
1740         int w = x2 - x1;
1741         int h = y2 - y1;
1742         int center_x = (x2 + x1) / 2;
1743         int center_y = (y2 + y1) / 2;
1744         int x_table[h / 2];
1745
1746 //printf("VFrame::draw_oval %d %d %d %d %d\n", __LINE__, x1, y1, x2, y2);
1747
1748         for(int i = 0; i < h / 2; i++) {
1749 // A^2 = -(B^2) + C^2
1750                 x_table[i] = (int)(sqrt(-SQR(h / 2 - i) + SQR(h / 2)) * w / h);
1751 //printf("VFrame::draw_oval %d i=%d x=%d\n", __LINE__, i, x_table[i]);
1752         }
1753
1754         for(int i = 0; i < h / 2 - 1; i++) {
1755                 int x3 = x_table[i];
1756                 int x4 = x_table[i + 1];
1757
1758                 if(x4 > x3 + 1) {
1759                         for(int j = x3; j < x4; j++) {
1760                                 draw_pixel(center_x + j, y1 + i);
1761                                 draw_pixel(center_x - j, y1 + i);
1762                                 draw_pixel(center_x + j, y2 - i - 1);
1763                                 draw_pixel(center_x - j, y2 - i - 1);
1764                         }
1765                 }
1766                 else {
1767                         draw_pixel(center_x + x3, y1 + i);
1768                         draw_pixel(center_x - x3, y1 + i);
1769                         draw_pixel(center_x + x3, y2 - i - 1);
1770                         draw_pixel(center_x - x3, y2 - i - 1);
1771                 }
1772         }
1773         
1774         draw_pixel(center_x, y1);
1775         draw_pixel(center_x, y2 - 1);
1776         draw_pixel(x1, center_y);
1777         draw_pixel(x2 - 1, center_y);
1778         draw_pixel(x1, center_y - 1);
1779         draw_pixel(x2 - 1, center_y - 1);
1780 }
1781
1782
1783 void VFrame::draw_arrow(int x1, int y1, int x2, int y2, int sz)
1784 {
1785         double angle = atan((float)(y2 - y1) / (float)(x2 - x1));
1786         double angle1 = angle + (float)145 / 360 * 2 * M_PI;
1787         double angle2 = angle - (float)145 / 360 * 2 * M_PI;
1788         int s = x2 < x1 ? -1 : 1;
1789         int x3 = x2 + s * (int)(sz * cos(angle1));
1790         int y3 = y2 + s * (int)(sz * sin(angle1));
1791         int x4 = x2 + s * (int)(sz * cos(angle2));
1792         int y4 = y2 + s * (int)(sz * sin(angle2));
1793
1794 // Main vector
1795         draw_line(x1, y1, x2, y2);
1796 //      draw_line(x1, y1 + 1, x2, y2 + 1);
1797
1798 // Arrow line
1799         if(abs(y2 - y1) || abs(x2 - x1)) draw_line(x2, y2, x3, y3);
1800 // Arrow line
1801         if(abs(y2 - y1) || abs(x2 - x1)) draw_line(x2, y2, x4, y4);
1802 }
1803
1804 void VFrame::draw_x(int x, int y, int sz)
1805 {
1806         draw_line(x-sz,y-sz, x+sz,y+sz);
1807         draw_line(x+sz,y-sz, x-sz,y+sz);
1808 }
1809 void VFrame::draw_t(int x, int y, int sz)
1810 {
1811         draw_line(x,y-sz, x,y+sz);
1812         draw_line(x+sz,y, x-sz,y);
1813 }
1814
1815