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