MediaServ: Update to new SENF library API
[mediaserv.git] / Server / StreamConnection.cc
1 // $Id$
2 //
3 // Copyright (C) 2006 
4
5 // Definition of non-inline non-template functions
6
7 #include "StreamConnection.hh"
8 //#include "StreamConnection.ih"
9
10 // Custom includes
11 #include <unistd.h>
12 #include "SimpleHTTPServer.hh"
13
14 //#include "StreamConnection.mpp"
15 #define prefix_
16 ///////////////////////////////cc.p////////////////////////////////////////
17
18 prefix_ g0dil::mediaserv::StreamConnection::StreamConnection(int fileFd,
19                                                              unsigned bytesPerSecond,
20                                                              ClientHandle client,
21                                                              unsigned bufferMSecs,
22                                                              Callback callback)
23     : fileFd_(fileFd), bytesPerSecond_(bytesPerSecond), client_(client),
24       bufferMSecs_(bufferMSecs), callback_(callback), bytesWritten_(0),
25       start_(senf::now()), bufferSize_(0), terminate_(false) 
26 {
27     fillBuffer();
28 }
29
30
31 prefix_ void g0dil::mediaserv::StreamConnection::start()
32 {
33     registerCallback();
34 }
35
36 prefix_ g0dil::mediaserv::StreamConnection::~StreamConnection()
37 {
38     unregisterCallback();
39     // FIXME: unregisterTimeout
40 }
41
42 prefix_ void g0dil::mediaserv::StreamConnection::fillBuffer()
43 {
44     bufferSize_ = ::read(fileFd_,buffer_,packetSize);
45     if (bufferSize_ < 0)
46         callback_();
47     else if (bufferSize_ < packetSize)
48         terminate_ = true;
49 }
50
51 prefix_ void g0dil::mediaserv::StreamConnection::callback(ClientHandle client,
52                                                     senf::Scheduler::EventId event)
53 {
54     if (event != senf::Scheduler::EV_WRITE) {
55         callback_();
56         return;
57     }
58     unsigned target (targetBytes());
59     if (target - bytesWritten_ >= bufferSize_) {
60         if (client_.write(buffer_,buffer_+bufferSize_) < buffer_+bufferSize_) {
61             callback_();
62             return;
63         }
64         bytesWritten_ += bufferSize_;
65         if (terminate_) {
66             callback_();
67             return;
68         } else
69             fillBuffer();
70     } else {
71         unregisterCallback();
72         registerTimeout(((bufferSize_-(target-bytesWritten_))*1000)/bytesPerSecond_);
73     }
74 }
75
76 prefix_ void g0dil::mediaserv::StreamConnection::timeout()
77 {
78     registerCallback();
79 }
80
81 ///////////////////////////////cc.e////////////////////////////////////////
82 #undef prefix_
83 //#include "StreamConnection.mpp"
84
85 \f
86 // Local Variables:
87 // mode: c++
88 // End: