summaryrefslogtreecommitdiff
path: root/TAO/orbsvcs/tests/AVStreams/mpeg/source/mpeg_server/Video_Server.cpp
blob: 19f59d672d2c77f355c48a7c7bdd23c76768b862 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
/* $Id$  */

/* Copyright (c) 1995 Oregon Graduate Institute of Science and Technology
 * P.O.Box 91000-1000, Portland, OR 97291, USA;
 * 
 * Permission to use, copy, modify, distribute, and sell this software and its 
 * documentation for any purpose is hereby granted without fee, provided that 
 * the above copyright notice appear in all copies and that both that 
 * copyright notice and this permission notice appear in supporting 
 * documentation, and that the name of O.G.I. not be used in advertising or 
 * publicity pertaining to distribution of the software without specific, 
 * written prior permission.  O.G.I. makes no representations about the 
 * suitability of this software for any purpose.  It is provided "as is" 
 * without express or implied warranty.
 * 
 * O.G.I. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING 
 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL 
 * O.G.I. BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY 
 * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 
 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Author: Shanwei Cen
 *         Department of Computer Science and Engineering
 *         email: scen@cse.ogi.edu
 */

#include "Video_Server.h"

// Global Methods

PLAYpara Video_Server::para;

// %% maybe put this in some class?
// this sends one frame
int
play_send (int debug)
{

  //  ACE_DEBUG((LM_DEBUG,"play_send: sending the frame \n"));
  int curGroup = Video_Timer_Global::timerGroup;
  int curFrame = Video_Timer_Global::timerFrame;
  int curHeader = Video_Timer_Global::timerHeader;
  char * sp;
    
  if (VIDEO_SINGLETON::instance ()->preGroup != curGroup || 
      curFrame != VIDEO_SINGLETON::instance ()->preFrame)
    {
      int sendStatus = -1;
      int frameStep = 1;
      if (debug)
        cerr <<  " curgroup = " << curGroup << endl ;
      if (curGroup == 0)
        {
      
          int i = curFrame + 1;
          while (i < VIDEO_SINGLETON::instance ()->firstPatternSize && 
                 !VIDEO_SINGLETON::instance ()->firstSendPattern[i])
            {
              frameStep ++;
              i++;
            }
        }
      else  /* (curGroup > 0) */
        {
          int i = curFrame + 1;
          sp = VIDEO_SINGLETON::instance ()->sendPattern + ((curGroup - 1) % VIDEO_SINGLETON::instance ()->sendPatternGops) * VIDEO_SINGLETON::instance ()->patternSize;
          while (i < VIDEO_SINGLETON::instance ()->patternSize && !sp[i])
            {
              frameStep ++;
              i++;
            }
        }
      if (curGroup == 0)
        {
          if (debug)
            cerr << "first : " <<
              VIDEO_SINGLETON::instance ()->firstSendPattern[curFrame] << endl;
          if (VIDEO_SINGLETON::instance ()->firstSendPattern[curFrame])
            sendStatus = 0;
          else /*  (!VIDEO_SINGLETON::instance ()->firstVIDEO_SINGLETON::instance ()->SendVIDEO_SINGLETON::Instance ()->Pattern[curFrame]) */
            {
              int i = curFrame - 1;
              while (i > 0 && !VIDEO_SINGLETON::instance ()->firstSendPattern[i])
                i--;
              if (i > VIDEO_SINGLETON::instance ()->preFrame)
                /* the frame (curGroup, i) hasn't been sent yet */
                {
                  sendStatus = 0;
                  curFrame = i;
                }
              else
                sendStatus = -1;
              if (debug)
                cerr << "SendStatus = " << sendStatus << endl;
            }
        }
      else if (sp[curFrame]) /* curGroup > 0 */
	sendStatus = 0;
      else /*  (!sp[curFrame]) */
        {
          int i = curFrame - 1;
          while (i > 0 && !sp[i])
            i--;
          if (curGroup == VIDEO_SINGLETON::instance ()->preGroup && i > VIDEO_SINGLETON::instance ()->preFrame)
            /* the frame (curGroup, i) hasn't been sent yet */
            {
              sendStatus = 0;
              curFrame = i;
            }
          else
            sendStatus = -1;
        }
      if (!sendStatus)
        {
          // Send the current video frame, calls send_to_network which
          // fragments and sends via blocking write .
          sendStatus = Video_Server::SendPacket(VIDEO_SINGLETON::instance ()->preHeader != curHeader,
                                  curGroup, curFrame,
                                  (VIDEO_SINGLETON::instance ()->currentUPF + VIDEO_SINGLETON::instance ()->addedUPF) * frameStep);
          if (!sendStatus)
            {
              VIDEO_SINGLETON::instance ()->preHeader = curHeader;
              VIDEO_SINGLETON::instance ()->preGroup = curGroup;
              VIDEO_SINGLETON::instance ()->preFrame = curFrame;
#ifdef STAT
              if (Video_Server::para.collectStat)
                {
                  int f = VIDEO_SINGLETON::instance ()->gopTable[curGroup].previousFrames + curFrame;
                  VIDEO_SINGLETON::instance ()->framesSent[f>>3] |= (1 << (f % 8));
                }
#endif
            }
        }
    }
  return 0;
}

int
fast_play_send (void)
{
  if (VIDEO_SINGLETON::instance ()->fast_preGroup != Video_Timer_Global::timerGroup)
    {
      Video_Server::SendPacket(VIDEO_SINGLETON::instance ()->fast_preHeader != Video_Timer_Global::timerHeader, Video_Timer_Global::timerGroup, 0,
		 VIDEO_SINGLETON::instance ()->fast_para.usecPerFrame * VIDEO_SINGLETON::instance ()->patternSize >> 2);
      VIDEO_SINGLETON::instance ()->fast_preHeader = Video_Timer_Global::timerHeader;
      VIDEO_SINGLETON::instance ()->fast_preGroup = Video_Timer_Global::timerGroup;
    }
  return 0;
}

// Video_Sig_Handler methods
// handles the timeout SIGALRM signal
// %% this should *not* register itself,but it should
// be registered by the Video_Server::run, alongwith
// the remaining  handlers.
Video_Sig_Handler::Video_Sig_Handler (Video_Control_Handler *vch)
  : vch_ (vch)
{
}

int
Video_Sig_Handler::register_handler (void)
{
  // Assign the Sig_Handler a dummy I/O descriptor.  Note that even
  // though we open this file "Write Only" we still need to use the
  // ACE_Event_Handler::NULL_MASK when registering this with the
  // ACE_Reactor (see below).
  this->handle_ = ACE_OS::open (ACE_DEV_NULL, O_WRONLY);
  ACE_ASSERT (this->handle_ != -1);

  // Register signal handler object.  Note that NULL_MASK is used to
  // keep the ACE_Reactor from calling us back on the "/dev/null"
  // descriptor.
  if (ACE_Reactor::instance ()->register_handler 
      (this, ACE_Event_Handler::NULL_MASK) == -1)
    ACE_ERROR_RETURN ((LM_ERROR, 
                       "%p\n", 
                       "register_handler"),
                      -1);

  // Create a sigset_t corresponding to the signals we want to catch.
  ACE_Sig_Set sig_set;

  //  sig_set.sig_add (SIGINT);
  // sig_set.sig_add (SIGQUIT);
  sig_set.sig_add (SIGALRM);  

  // Register the signal handler object to catch the signals.
  if (ACE_Reactor::instance ()->register_handler (sig_set, 
                                                  this) == -1)
    ACE_ERROR_RETURN ((LM_ERROR, 
                       "%p\n", 
                       "register_handler"),
                      -1);

  return 0;
}
// Called by the ACE_Reactor to extract the fd.

ACE_HANDLE
Video_Sig_Handler::get_handle (void) const
{
  return this->handle_;
}

int 
Video_Sig_Handler::handle_input (ACE_HANDLE)
{
  ACE_DEBUG ((LM_DEBUG, "(%t) handling asynchonrous input...\n"));
  return 0;
}

int 
Video_Sig_Handler::shutdown (ACE_HANDLE, ACE_Reactor_Mask)
{
  ACE_DEBUG ((LM_DEBUG, "(%t) closing down Sig_Handler...\n"));
  return 0;
}

// This method handles all the signals that are being caught by this
// object.  In our simple example, we are simply catching SIGALRM,
// SIGINT, and SIGQUIT.  Anything else is logged and ignored.
//
// There are several advantages to using this approach.  First, 
// the behavior triggered by the signal is handled in the main event
// loop, rather than in the signal handler.  Second, the ACE_Reactor's 
// signal handling mechanism eliminates the need to use global signal 
// handler functions and data. 

int
Video_Sig_Handler::handle_signal (int signum, siginfo_t *, ucontext_t *)
{
  //  ACE_DEBUG ((LM_DEBUG, "(%t) received signal %S\n", signum));

  switch (signum)
    {
    case SIGALRM:
      // Handle the timeout
      Video_Timer_Global::timerHandler (SIGALRM);
      // send the frame
      //      cerr << "current state = " << this->vch_->get_state ()->get_state ();
      switch (this->vch_->get_state ()->get_state ())
        {
        case Video_Control_State::VIDEO_PLAY:
          play_send ();
          break;
        case Video_Control_State::VIDEO_FAST_FORWARD:
          // this handles the forward play case!
          fast_play_send ();
          break;
        case Video_Control_State::VIDEO_FAST_BACKWARD:
          // this handles the backward play case!
          fast_play_send ();
          break;
        default:
          break;
        }
      break;
    default: 
      ACE_DEBUG ((LM_DEBUG, 
		  "(%t) %S: not handled, returning to program\n", 
                  signum));
      break;
    }
  return 0;
}

// Video_Data_Handler methods

Video_Data_Handler::Video_Data_Handler (int video_data_fd,
                                        Video_Control_Handler *vch)
  : data_handle_ (video_data_fd),
    vch_ (vch)
{
}

ACE_HANDLE
Video_Data_Handler::get_handle (void) const
{
  return this->data_handle_ ;
}

int
Video_Data_Handler::handle_input (ACE_HANDLE handle)
{
  fprintf (stderr,"Video_Data_Handler::handle_input ()\n");
  
  switch (this->vch_->get_state ()->get_state ())
    {
    case Video_Control_State::VIDEO_PLAY:
      GetFeedBack ();
      play_send (); // simulating the for loop in playvideo () in vs.cpp
      break;
    case Video_Control_State::VIDEO_FAST_FORWARD:
    case Video_Control_State::VIDEO_FAST_BACKWARD:
      GetFeedBack ();
      fast_play_send (); // simulating the for loop in fast_play
      break;
    }
  return 0;
}  

// Video_Control_Handler methods

Video_Control_Handler::Video_Control_Handler (int control_fd)
  : control_handle_ (control_fd)
{
  VIDEO_CONTROL_HANDLER_INSTANCE::instance ()->set_video_control_handler (this);
}

ACE_HANDLE
Video_Control_Handler::get_handle (void) const
{
  return this->control_handle_ ;
}

int
Video_Control_Handler::handle_input (ACE_HANDLE handle)
{
  return this->state_->handle_input (handle);
  // state pattern
}

Video_Control_State *
Video_Control_Handler::get_state (void)
{
  return this->state_;
}

void
Video_Control_Handler::change_state (Video_Control_State *state)
{
  ACE_DEBUG ((LM_DEBUG,
              "Video_Control_Handler::Changing to state %d\n",
              state->get_state ()));
  this->state_ = state;
}

// ----------------------------------------------------------------------

Video_Control_Handler_Instance::Video_Control_Handler_Instance (void)
{
}

void
Video_Control_Handler_Instance::set_video_control_handler (Video_Control_Handler *h)
{
  this->video_control_handler_ = h;
}

Video_Control_Handler *
Video_Control_Handler_Instance::get_video_control_handler (void)
{
  return this->video_control_handler_;
}
// ----------------------------------------------------------------------

// Video_Server methods

// Do-nothing default constructor.
Video_Server::Video_Server ()
{
}

Video_Server::Video_Server (int ctr_fd,
                            int data_fd,
                            int rttag,
                            int max_pkt_size)
  : data_handler_ (0),
    control_handler_ (0),
    sig_handler_ (0)
{
  this->init (ctr_fd,
              data_fd,
              rttag,
              max_pkt_size);
}

// initialize VIDEO_SINGLETON::instance ()
// creates a data and control handler for the video
// server. the control handler will accept
// commands over TCP, and the data handler will
// send data packets and recieve feedback packets
// from the client
// the reactor_ also gets initialized here
int
Video_Server::init (int ctr_fd,
                    int data_fd,
                    int rttag,
                    int max_pkt_size)
{
  this->reactor_ = ACE_Reactor::instance ();

  ACE_NEW_RETURN (this->control_handler_, 
                  Video_Control_Handler (ctr_fd),
                  -1);

  ACE_NEW_RETURN (this->data_handler_ ,
                  Video_Data_Handler (data_fd,
                                      this->control_handler_),
                  -1);

  ACE_NEW_RETURN (this->sig_handler_, 
                  Video_Sig_Handler (this->control_handler_),
                  -1);

  int result;

  VIDEO_SINGLETON::instance ()->serviceSocket = ctr_fd;
  VIDEO_SINGLETON::instance ()->videoSocket = data_fd;
  VIDEO_SINGLETON::instance ()->conn_tag = max_pkt_size;
  
  if (max_pkt_size > 0) VIDEO_SINGLETON::instance ()->msgsize = max_pkt_size;
  else if (max_pkt_size < 0) VIDEO_SINGLETON::instance ()->msgsize = - max_pkt_size;
  else VIDEO_SINGLETON::instance ()->msgsize = 1024 * 1024;
  /*
    SFprintf(stderr, "VS VIDEO_SINGLETON::instance ()->msgsize = %d\n", VIDEO_SINGLETON::instance ()->msgsize);
  */
  VIDEO_SINGLETON::instance ()->msgsize -= sizeof(VideoMessage);
  
  VIDEO_SINGLETON::instance ()->start_time = time(NULL);

  atexit(on_exit_routine);

  VIDEO_SINGLETON::instance ()->lastRef[0] = VIDEO_SINGLETON::instance ()->lastRef[1] = -1;
  VIDEO_SINGLETON::instance ()->lastRefPtr = 0;

  INITvideo();

  if (rttag) {
    if (SetRTpriority("VS", 0) == -1) rttag = 0;
  }
  // sets the video control handler state to be waiting

  this->control_handler_->change_state
    (VIDEO_CONTROL_WAITING_STATE::instance ());
  return 0;
}

// %% currently this only registers handlers
// and handles the FIRST command. that needs
// to be changed, and then maybe this 
// needs tobe renamed to register_handles or something
// like that
int
Video_Server::run (void)
{
  int result;

  // Register the event handlers with the default ACE_REACTOR.


  // first the data handler, i.e. UDP
  result = this->reactor_->register_handler (this->data_handler_, 
                                             ACE_Event_Handler::READ_MASK);
  if (result < 0)
      ACE_ERROR_RETURN ((LM_ERROR,
                         "(%P|%t) register_handler for data_handler failed\n"),
                        result);
  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t) registered fd for data handler = (%d)\n",
              this->data_handler_->get_handle ()));


  // next, the control handler, i.e. TCP
  result = this->reactor_->register_handler (this->control_handler_,
                                             ACE_Event_Handler::READ_MASK);

  
  if (result < 0)
      ACE_ERROR_RETURN ((LM_ERROR,
                         "(%P|%t) register_handler for data_handler failed\n"),
                        result);
  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t) registered fd for control handler = (%d)\n",
              this->control_handler_->get_handle ()));

  // finally, the signal handler, for periodic transmission
  // of packets
  result = this->sig_handler_->register_handler ();

  
  if (result < 0)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "(%P|%t) register_handler for sig_handler"
                       "failed!\n"),
                      -1);

  return 0;
}

int
Video_Server::init_play (void)
{
  int result;

  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t) Video_Server::play ()"));

  // this gets the parameters for the play command
  result = Video_Server::CmdRead((char *)&para, sizeof(para));
  if (result != 0)
    return result;
#ifdef NeedByteOrderConversion
  para.sn = ntohl(para.sn);
  para.VIDEO_SINGLETON::instance ()->nextFrame = ntohl(para.VIDEO_SINGLETON::instance ()->nextFrame);
  para.usecPerFrame = ntohl(para.usecPerFrame);
  para.framesPerSecond = ntohl(para.framesPerSecond);
  para.VIDEO_SINGLETON::instance ()->frameRateLimit1000 = ntohl(para.VIDEO_SINGLETON::instance ()->frameRateLimit1000);
  para.collectStat = ntohl(para.collectStat);
  para.VIDEO_SINGLETON::instance ()->sendPatternGops = ntohl(para.VIDEO_SINGLETON::instance ()->sendPatternGops);
  para.VIDEO_SINGLETON::instance ()->VStimeAdvance = ntohl(para.VIDEO_SINGLETON::instance ()->VStimeAdvance);
#endif

  VIDEO_SINGLETON::instance ()->frameRateLimit = para.frameRateLimit1000 / 1000.0;
  VIDEO_SINGLETON::instance ()->cmdsn = para.sn;
  VIDEO_SINGLETON::instance ()->currentUPF = para.usecPerFrame;
  VIDEO_SINGLETON::instance ()->VStimeAdvance = para.VStimeAdvance;

  {
    int ts = htonl(get_usec());
    Video_Server::CmdWrite((char *)&ts, sizeof(int));
  }
  
  if (VIDEO_SINGLETON::instance ()->live_source || VIDEO_SINGLETON::instance ()->video_format != VIDEO_MPEG1) {
    if (VIDEO_SINGLETON::instance ()->live_source) 
      PLAYliveVideo (&para);
    return 0;
  }
  
  fprintf(stderr, "VIDEO_SINGLETON::instance ()->VStimeAdvance from client: %d\n", VIDEO_SINGLETON::instance ()->VStimeAdvance);
  
  VIDEO_SINGLETON::instance ()->sendPatternGops = para.sendPatternGops;
  ComputeFirstSendPattern(VIDEO_SINGLETON::instance ()->frameRateLimit);
#ifdef STAT
  if (para.collectStat)
    memset(VIDEO_SINGLETON::instance ()->framesSent, 0, (VIDEO_SINGLETON::instance ()->numF + 7)>>3);
#endif
  CheckFrameRange(para.nextFrame);
  Video_Timer_Global::timerFrame = para.nextFrame;
  Video_Timer_Global::timerGroup = FrameToGroup(&Video_Timer_Global::timerFrame);
  Video_Timer_Global::timerHeader = VIDEO_SINGLETON::instance ()->gopTable[Video_Timer_Global::timerGroup].systemHeader;
  memcpy(VIDEO_SINGLETON::instance ()->sendPattern, para.sendPattern, PATTERN_SIZE);
  result = SendReferences(Video_Timer_Global::timerGroup, Video_Timer_Global::timerFrame);
  if (result < 0)
    return result;
  Video_Timer_Global::StartTimer ();

  // Sends the first frame of the video...
  result = play_send (0);
  return 0;
}

int
Video_Server::SendPacket (int shtag,int gop,int frame,int timeToUse)
/* frame maybe out of range (PLAY, STEP), in this case, END_SEQ is sent
   to force display of last frame in VD */
{
  char * buf = ((char *) VIDEO_SINGLETON::instance ()->packet) + sizeof(VideoPacket);
  int f = VIDEO_SINGLETON::instance ()->gopTable[gop].previousFrames + frame;
  int sh = VIDEO_SINGLETON::instance ()->gopTable[gop].systemHeader;
  /*
  SFprintf(stderr, "VS to send VIDEO_SINGLETON::instance ()->packet gop-%d, frame-%d.\n", gop, frame);
  */

  VIDEO_SINGLETON::instance ()->packet->currentUPF = ntohl(VIDEO_SINGLETON::instance ()->currentUPF);

  if (frame >= VIDEO_SINGLETON::instance ()->gopTable[gop].totalFrames)
  {
    VIDEO_SINGLETON::instance ()->packet->cmd = htonl(VIDEO_SINGLETON::instance ()->cmd);
    VIDEO_SINGLETON::instance ()->packet->cmdsn = htonl(VIDEO_SINGLETON::instance ()->cmdsn);
    VIDEO_SINGLETON::instance ()->packet->sh = htonl(sh);
    VIDEO_SINGLETON::instance ()->packet->gop = htonl(gop);
    VIDEO_SINGLETON::instance ()->packet->frame = htonl(VIDEO_SINGLETON::instance ()->numF);
    VIDEO_SINGLETON::instance ()->packet->display = htonl(VIDEO_SINGLETON::instance ()->numF-1);
    VIDEO_SINGLETON::instance ()->packet->future = htonl((unsigned)-1);
    VIDEO_SINGLETON::instance ()->packet->past = htonl((unsigned)-1);
    VIDEO_SINGLETON::instance ()->packet->dataBytes = htonl(4);
    *(int*)((char*)VIDEO_SINGLETON::instance ()->packet + sizeof(*VIDEO_SINGLETON::instance ()->packet)) = htonl(SEQ_END_CODE);

    return send_to_network(timeToUse);
  }

  if (frame)
    shtag = 0;
  else if (VIDEO_SINGLETON::instance ()->needHeader)
  {
    shtag = 1;
    VIDEO_SINGLETON::instance ()->needHeader = 0;
  }
  
  VIDEO_SINGLETON::instance ()->packet->cmd = htonl(VIDEO_SINGLETON::instance ()->cmd);
  VIDEO_SINGLETON::instance ()->packet->cmdsn = htonl(VIDEO_SINGLETON::instance ()->cmdsn);
  VIDEO_SINGLETON::instance ()->packet->sh = htonl(sh);
  VIDEO_SINGLETON::instance ()->packet->gop = htonl(gop);
  VIDEO_SINGLETON::instance ()->packet->frame = htonl(f);
  if (VIDEO_SINGLETON::instance ()->frameTable[f].type == 'B')
  {
    int pre1 = -1, pre2 = -1, i = f;
    while (i>0)
      if (VIDEO_SINGLETON::instance ()->frameTable[--i].type != 'B')
      {
	pre1 = i;
	break;
      }
    while (i>0)
      if (VIDEO_SINGLETON::instance ()->frameTable[--i].type != 'B')
      {
	pre2 = i;
	break;
      }
    if (pre2 ==  -1)
    {
      /*
      fprintf(stderr,
	      "frame %d-%d (%d) is a B without past ref, no to be sent.\n",
	      gop, frame, f);
       */
      return -1;
    }
    if (pre1 != VIDEO_SINGLETON::instance ()->lastRef[VIDEO_SINGLETON::instance ()->lastRefPtr] ||
	pre2 != VIDEO_SINGLETON::instance ()->lastRef[1 - VIDEO_SINGLETON::instance ()->lastRefPtr])
    {
      /*
      fprintf(stderr,
	      "send of B frame %d gaveup for past %d/future %d ref not sent.\n",
	      f, pre2, pre1);
       */
      return -1;
    }
    VIDEO_SINGLETON::instance ()->packet->display = htonl(f);
    VIDEO_SINGLETON::instance ()->packet->future = htonl(pre1);
    VIDEO_SINGLETON::instance ()->packet->past = htonl(pre2);
  }
  else
  {
    int next = f;
    int pre = f;

    while (next < VIDEO_SINGLETON::instance ()->numF && VIDEO_SINGLETON::instance ()->frameTable[++next].type == 'B');
    while (pre > 0 && VIDEO_SINGLETON::instance ()->frameTable[--pre].type == 'B');
    if (VIDEO_SINGLETON::instance ()->frameTable[f].type == 'P' && pre != VIDEO_SINGLETON::instance ()->lastRef[VIDEO_SINGLETON::instance ()->lastRefPtr])
    {
      /*
      fprintf(stderr,
	      "send of P frame %d gaveup for past ref %d not sent.\n",
	      f, pre);
      fprintf(stderr, "ref0=%d, ref1=%d, ptr=%d.\n",
	      VIDEO_SINGLETON::instance ()->lastRef[0], VIDEO_SINGLETON::instance ()->lastRef[1], VIDEO_SINGLETON::instance ()->lastRefPtr);
       */
      return -1;
    }
    VIDEO_SINGLETON::instance ()->packet->display = htonl(next);
    VIDEO_SINGLETON::instance ()->packet->future = htonl((unsigned)-1);
    VIDEO_SINGLETON::instance ()->packet->past = htonl(VIDEO_SINGLETON::instance ()->frameTable[f].type == 'P' ? pre : (unsigned)-1);
  }
  {
    char * ptr = buf;
    int size = 0, offset = 0, i;
    if (shtag)   /* send system header */
    {
      size = VIDEO_SINGLETON::instance ()->systemHeader[sh].size;
      FileRead(VIDEO_SINGLETON::instance ()->systemHeader[sh].offset, ptr, size);
      ptr += size;
    }
    if (!frame)   /* send gop header */
    {
      size = VIDEO_SINGLETON::instance ()->gopTable[gop].headerSize;
      FileRead(VIDEO_SINGLETON::instance ()->gopTable[gop].offset, ptr, size);
      ptr += size;
    }
    size = VIDEO_SINGLETON::instance ()->frameTable[f].size;
    for (i=VIDEO_SINGLETON::instance ()->gopTable[gop].previousFrames; i<f; i++)
      offset += VIDEO_SINGLETON::instance ()->frameTable[i].size;
    FileRead((VIDEO_SINGLETON::instance ()->gopTable[gop].firstIoffset + offset), ptr, size);
    ptr += size;
    VIDEO_SINGLETON::instance ()->packet->dataBytes = htonl(ptr - buf);
  }

  {
    int sent = send_to_network(timeToUse);
    if (!sent)
    {
      /*
      fprintf(stderr, "%c%d\n", VIDEO_SINGLETON::instance ()->frameTable[f].type, f);
      fprintf(stderr, "%c frame %d sent.\n", VIDEO_SINGLETON::instance ()->frameTable[f].type, f);
      */
      if (VIDEO_SINGLETON::instance ()->frameTable[f].type != 'B')
      {
	VIDEO_SINGLETON::instance ()->lastRefPtr = 1 - VIDEO_SINGLETON::instance ()->lastRefPtr;
	VIDEO_SINGLETON::instance ()->lastRef[VIDEO_SINGLETON::instance ()->lastRefPtr] = f;
      }
    }
    return sent;
  }
}

int
Video_Server::CmdRead (char *buf, int psize)
{
  int res = wait_read_bytes (VIDEO_SINGLETON::instance ()->serviceSocket, 
                             buf, 
                             psize);
  if (res == 0) return(1);
  if (res == -1) {
    fprintf(stderr, "VS error on read VIDEO_SINGLETON::instance ()->cmdSocket, size %d", psize);
    perror("");
    return(-1);
  }
  return 0;
}

void
Video_Server::CmdWrite(char *buf, int size)
{
  int res = wait_write_bytes(VIDEO_SINGLETON::instance ()->serviceSocket, buf, size);
  if (res == -1) {
    if (errno != EPIPE) perror("VS writes to VIDEO_SINGLETON::instance ()->serviceSocket");
    exit (errno != EPIPE);
  }
}

void
Video_Server::on_exit_routine(void)
{
  struct sockaddr_in peeraddr_in;
  int size = sizeof(peeraddr_in);
  /*
  if (!VIDEO_SINGLETON::instance ()->normalExit) {
    fprintf(stderr, "VS exitting abnormally, dump core...\n");
    kill(getpid(), SIGSEGV);
    usleep(2000000);
  }
  */
  /*
  fprintf(stderr, "A VS session terminated.\n");
  */
  if (getpeername(VIDEO_SINGLETON::instance ()->serviceSocket,
		  (struct sockaddr *)&peeraddr_in, &size) == 0 &&
      peeraddr_in.sin_family == AF_INET) {
    if (strncmp(inet_ntoa(peeraddr_in.sin_addr), "129.95.50", 9)) {
      struct hostent *hp;
      time_t val = time(NULL);
      char * buf = ctime(&VIDEO_SINGLETON::instance ()->start_time);
      
      hp = gethostbyaddr((char *)&(peeraddr_in.sin_addr), 4, AF_INET);
      buf[strlen(buf)-1] = 0;
      printf("%s: %s %3dm%02ds %dP %s\n",
	     buf,
	     hp == NULL ? inet_ntoa(peeraddr_in.sin_addr) : hp->h_name,
	     (val - VIDEO_SINGLETON::instance ()->start_time) / 60, (val - VIDEO_SINGLETON::instance ()->start_time) % 60,
	     VIDEO_SINGLETON::instance ()->pkts_sent, VIDEO_SINGLETON::instance ()->videoFile);
    }
  }
  /*
  ComCloseConn(VIDEO_SINGLETON::instance ()->serviceSocket);
  ComCloseConn(VIDEO_SINGLETON::instance ()->videoSocket);*/
}

int
Video_Server::position (void)
{
  int result;
  POSITIONpara pos_para;
  /*
  fprintf(stderr, "POSITION . . .\n");
  */
  result = CmdRead((char *)&pos_para, sizeof(pos_para));
  if (result != 0)
    return result;

  if (VIDEO_SINGLETON::instance ()->live_source) return 0;
  
#ifdef NeedByteOrderConversion
  pos_para.nextGroup = ntohl(pos_para.nextGroup);
  pos_para.sn = ntohl(pos_para.sn);
#endif
  
  CheckGroupRange(pos_para.nextGroup);
  VIDEO_SINGLETON::instance ()->cmdsn = pos_para.sn;
  result = SendPacket(VIDEO_SINGLETON::instance ()->numS>1 || pos_para.nextGroup == 0, pos_para.nextGroup, 0, 0);
  return result;
}

int
Video_Server::step_video()
{
  int group;
  STEPpara step_para;
  int tag = 0;
  int result;

  result = CmdRead((char *)&step_para, sizeof(step_para));
  if (result != 0)
    return result;
#ifdef NeedByteOrderConversion
  step_para.sn = ntohl(step_para.sn);
  step_para.VIDEO_SINGLETON::instance ()->nextFrame = ntohl(step_para.VIDEO_SINGLETON::instance ()->nextFrame);
#endif

  VIDEO_SINGLETON::instance ()->cmdsn = step_para.sn;

  if (!VIDEO_SINGLETON::instance ()->live_source) {
    if (step_para.nextFrame >= VIDEO_SINGLETON::instance ()->numF)  /* send SEQ_END */
    {
      tag = 1;
      step_para.nextFrame --;
    }
    /*
    fprintf(stderr, "STEP . . .frame-%d\n", step_para.VIDEO_SINGLETON::instance ()->nextFrame);
    */
    CheckFrameRange(step_para.nextFrame);
    group = FrameToGroup(&step_para.nextFrame);
    if (VIDEO_SINGLETON::instance ()->precmd != CmdSTEP && !tag ) {
      result = SendReferences(group, step_para.nextFrame);
      if (result < 0 )
        return result;
    }
  }
  if (VIDEO_SINGLETON::instance ()->live_source) StartPlayLiveVideo();
  
  if (VIDEO_SINGLETON::instance ()->live_source) {
    SendPicture(&step_para.nextFrame);
  }
  else if (VIDEO_SINGLETON::instance ()->video_format == VIDEO_MPEG1) {
    SendPacket(VIDEO_SINGLETON::instance ()->numS>1, group, tag ? VIDEO_SINGLETON::instance ()->numF : step_para.nextFrame, 0);
  }
  else {
    fprintf(stderr, "VS: wierd1\n");
  }
  
  if (VIDEO_SINGLETON::instance ()->live_source) StopPlayLiveVideo();
  return 0;
}

int
Video_Server::init_fast_play (void)
{
  int result;
  
  result = CmdRead((char *)&VIDEO_SINGLETON::instance ()->fast_para, sizeof(VIDEO_SINGLETON::instance ()->fast_para));
  if (result != 0)
    return result;
#ifdef NeedByteOrderConversion
  VIDEO_SINGLETON::instance ()->fast_para.sn = ntohl(VIDEO_SINGLETON::instance ()->fast_para.sn);
  VIDEO_SINGLETON::instance ()->fast_para.VIDEO_SINGLETON::instance ()->nextGroup = ntohl(VIDEO_SINGLETON::instance ()->fast_para.VIDEO_SINGLETON::instance ()->nextGroup);
  VIDEO_SINGLETON::instance ()->fast_para.usecPerFrame = ntohl(VIDEO_SINGLETON::instance ()->fast_para.usecPerFrame);
  VIDEO_SINGLETON::instance ()->fast_para.framesPerSecond = ntohl(VIDEO_SINGLETON::instance ()->fast_para.framesPerSecond);
  VIDEO_SINGLETON::instance ()->fast_para.VIDEO_SINGLETON::instance ()->VStimeAdvance = ntohl(VIDEO_SINGLETON::instance ()->fast_para.VIDEO_SINGLETON::instance ()->VStimeAdvance);
#endif

  if (VIDEO_SINGLETON::instance ()->live_source) return 0;
  
  VIDEO_SINGLETON::instance ()->VStimeAdvance = VIDEO_SINGLETON::instance ()->fast_para.VStimeAdvance;
  /*
  fprintf(stderr, "VIDEO_SINGLETON::instance ()->VStimeAdvance from client: %d\n", VIDEO_SINGLETON::instance ()->VStimeAdvance);
  */
  CheckGroupRange(VIDEO_SINGLETON::instance ()->fast_para.nextGroup);
  VIDEO_SINGLETON::instance ()->cmdsn = VIDEO_SINGLETON::instance ()->fast_para.sn;
  Video_Timer_Global::timerGroup = VIDEO_SINGLETON::instance ()->fast_para.nextGroup;
  Video_Timer_Global::timerFrame = 0;
  Video_Timer_Global::timerHeader = VIDEO_SINGLETON::instance ()->gopTable[Video_Timer_Global::timerGroup].systemHeader;
  VIDEO_SINGLETON::instance ()->currentUPF = VIDEO_SINGLETON::instance ()->fast_para.usecPerFrame;
  Video_Timer_Global::StartTimer();

  fast_play_send ();
  return 0;
}

int
Video_Server::fast_forward (void)
{
  return Video_Server::init_fast_play ();
}

int
Video_Server::fast_backward (void)
{
  return Video_Server::init_fast_play ();
}

int
Video_Server::stat_stream(void)
{
  int i, j = 0;
  for (i = 0; i < VIDEO_SINGLETON::instance ()->numF; i++)
  {
    short size = htons(VIDEO_SINGLETON::instance ()->frameTable[i].size);
    char type = VIDEO_SINGLETON::instance ()->frameTable[i].type;
    if (i == VIDEO_SINGLETON::instance ()->gopTable[j].previousFrames)
    {
      type = tolower(type);
      j ++;
    }
    CmdWrite((char *)&type, 1);
    CmdWrite((char *)&size, 2);
  }
  return 0;
}

int
Video_Server::stat_sent(void)
{
#ifdef STAT
  CmdWrite((char *)VIDEO_SINGLETON::instance ()->framesSent, (VIDEO_SINGLETON::instance ()->numF + 7) / 8);
#else
  int i;
  char zeroByte = 0;
  for (i = 0; i < (VIDEO_SINGLETON::instance ()->numF + 7) / 8; i++)
    CmdWrite((char *)&zeroByte, 1);
#endif
  return 0;
}

// Destructor
Video_Server::~Video_Server ()
{
  if (this->data_handler_ != 0)
    delete this->data_handler_ ;
  if (this->control_handler_ != 0)
    delete this->control_handler_ ;
  if (this->sig_handler_ != 0)
    delete this->sig_handler_ ;
}