summaryrefslogtreecommitdiff
path: root/p2pvr/daemon/schedules.cpp
blob: d948603ec3166f378e1ae542f5cf8e8b1241e486 (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
#include "schedules.h"
#include <logger.h>
#include <Ice/Ice.h>
#include "commonHelpers.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <factory.impl.h>
#include <slicer/db/sqlSelectDeserializer.h>
#include <slicer/db/sqlInsertSerializer.h>
#include <slicer/db/sqlUpdateSerializer.h>
#include <slicer/db/sqlTablePatchSerializer.h>
#include <tablepatch.h>
#include <p2pvr-int.h>

#include "sql/schedules/getCandidates.sql.h"
#include "sql/schedules/deleteById.sql.h"
#include "sql/schedules/selectAll.sql.h"
#include "sql/schedules/selectById.sql.h"
#include "sql/schedules/scheduledToRecord.sql.h"

namespace po = boost::program_options;

namespace P2PVR {
IceTray::Logging::LoggerPtr SchedulesI::logger(LOGMANAGER()->getLogger<SchedulesI>());

SchedulesI::Options::Options() :
	IceTray::Options("P2PVR Scheduler options")
{
}

ICETRAY_OPTIONS(SchedulesI::Options,
		("p2pvr.scheduler.algorithm", po::value(&SchedulerAlgorithm)->default_value("BitDumb"),
		 "Implementation of episode group scheduler problem solver")
)

Showing::Showing(unsigned int e, unsigned int t, unsigned int sc, datetime start, datetime stop, int p, const Episode * ep) :
	episode(ep),
	eventUid(e),
	priority(p),
	scheduleId(sc),
	transportStreamId(t),
	startTime(start),
	stopTime(stop),
	period(start, stop)
{
}

Episode::Episode(const std::string & w) :
	priority(0),
	what(w)
{
}

EpisodeGroup::EpisodeGroup() :
	tuners(1),
	sumTimeToStart(0),
	score(0)
{
}

bool
EpisodeGroup::IsShowingListValid(const Showings & showings) const
{
	struct TransOffset {
		unsigned int trans;
		char offset;
	};
	typedef std::multimap<datetime, TransOffset> Periods;
	typedef std::map<int, unsigned char> Usage;

	Periods periods;
	Usage usage;

	for (const auto & s : showings) {
		if (s) {
			periods.insert(Periods::value_type(s->startTime, {s->transportStreamId, 1}));
			periods.insert(Periods::value_type(s->stopTime, {s->transportStreamId, -1}));
		}
	}
	bool result = true;
	for (const auto & p : periods) {
		auto & u = usage[p.second.trans];
		u += p.second.offset;
		if (std::count_if(usage.begin(), usage.end(), [](const Usage::value_type & uv) { return uv.second > 0;}) > tuners) {
			result = false;
			break;
		}
	}
	periods.clear();
	usage.clear();
	return result;
}

template<typename T>
inline
bool NotNull(const T & p)
{
	return p != NULL;
}

class SumTimeToStart {
	public:
		SumTimeToStart(time_t & t) :
			total(t),
			now(boost::posix_time::second_clock::universal_time())
		{
			total = 0;
		}
		inline void operator()(const ShowingPtr & s) const
		{
			if (s) {
				total += std::min<time_t>((now - s->startTime).seconds(), 0);
			}
		}
	public:
		time_t & total;
		datetime now;
};

const Showings &
EpisodeGroup::Solve()
{
	SelectShowings();
	return selected;
}

void
EpisodeGroup::Suggest(const Showings & showings)
{
	unsigned int c = 0;
	std::for_each(showings.begin(), showings.end(), [&c](const ShowingPtr & s) { if (s) c+= s->episode->priority; });
	if (c >= score) {
		time_t stt;
		std::for_each(showings.begin(), showings.end(), SumTimeToStart(stt));
		if (stt < sumTimeToStart || (stt == sumTimeToStart && c > score)) {
			if (IsShowingListValid(showings)) {
				selected = showings;
				score = c;
				sumTimeToStart = stt;
			}
		}
	}
}

EpisodeGroup::SuggestionResult
EpisodeGroup::SuggestWithFeedback(const Showings & showings)
{
	if (IsShowingListValid(showings)) {
		unsigned int c = 0;
		std::for_each(showings.begin(), showings.end(), [&c](const ShowingPtr & s) { if (s) c+= s->episode->priority; });
		if (c >= score) {
			time_t stt;
			std::for_each(showings.begin(), showings.end(), SumTimeToStart(stt));
			if (stt < sumTimeToStart) {
				selected = showings;
				score = c;
				sumTimeToStart = stt;
				return SuggestionValidAndAccepted;
			}
		}
		return SuggestionValid;
	}
	else {
		return SuggestionInvalid;
	}
}

SchedulesI::SchedulesI(IceTray::DatabasePoolPtr db) :
	IceTray::AbstractDatabaseClient(db)
{
}

void
SchedulesI::GetEpisodeIntersects(Episodes & all, Episodes & grouped)
{
	for (Episodes::iterator aei = all.begin(); aei != all.end(); aei++) {
		const auto & ae = *aei;
		for (const auto & ge : grouped) {
			for (const auto & gs : ge->showings) {
				for (const auto & as : ae->showings) {
					if (gs->period.intersects(as->period)) {
						logger->messagebf(LOG::DEBUG, "	added %s", ae->what);
						grouped.push_back(ae);
						all.erase(aei);
						GetEpisodeIntersects(all, grouped);
						return;
					}
				}
			}
		}
	}
}

void
SchedulesI::DoReschedule(const Ice::Current & ice)
{
	auto ic = ice.adapter->getCommunicator();
	auto devs = P2PVR::TunersPrx::checkedCast(ice.adapter->createProxy(ic->stringToIdentity("Devices")));
	unsigned int tunerCount = devs->TunerCount();

	// Load list from database
	auto episodes = fetch<ScheduleCandidates>(P2PVR::sql::schedules::getCandidates);

	Episodes scheduleList;
	Showings allShowings;
	EpisodePtr cur;
	int minPriority = 0;
	for (const auto & c : episodes) {
		if (!cur || cur->what != c->What) {
			cur = new Episode(c->What);
			scheduleList.push_back(cur);
		}
		ShowingPtr s = new Showing(c->EventUid, c->TransportStreamId, c->ScheduleId,
				*c->StartTime, *c->StopTime, c->Priority, cur.get());
		minPriority = std::min(minPriority, s->priority);
		cur->showings.push_back(s);
		allShowings.push_back(s);
	}
	logger->messagebf(LOG::DEBUG, "%d episodes created, %s showings", scheduleList.size(), allShowings.size());
	for (const auto & e : scheduleList) {
		logger->messagebf(LOG::DEBUG, "	%s", e->what);
		for (const auto & s : e->showings) {
			s->priority += 1 - minPriority;
			e->priority += s->priority;
		}
		e->priority /= e->showings.size();
	}

	P2PVR::ScheduledToRecordList records;
	// Solve
	while (!scheduleList.empty()) {
		auto work = scheduleList.begin();
		logger->messagebf(LOG::DEBUG, "start %s", (*work)->what);
		Episodes group;
		group.push_back(*work);
		scheduleList.erase(work);
		GetEpisodeIntersects(scheduleList, group);
		std::sort(group.begin(), group.end(), [](const EpisodePtr & a, const EpisodePtr & b) {
				if (a->priority > b->priority) return true;
				if (a->priority < b->priority) return false;
				return a->what < b->what;
			});

		logger->messagebf(LOG::DEBUG, "group created with %d episodes", group.size());
		double total = 1;
		// Measure and add the optional to not record
		for (const auto & e : group) {
			logger->messagebf(LOG::DEBUG, "	%d * %d:%s", e->showings.size(), e->priority, e->what);
			e->showings.push_back(NULL);
			total *= e->showings.size();
		}
		logger->messagebf(LOG::DEBUG, "group complexity of %d options", total);

		EpisodeGroupPtr sched = EpisodeGroupPtr(EpisodeGroupFactory::createNew(options->SchedulerAlgorithm, group));
		sched->tuners = tunerCount;
		std::set<ShowingPtr> selected;
		for (const auto & s : sched->Solve()) {
			if (s) selected.insert(s);
		}

		for (const auto & c : group) {
			logger->messagebf(LOG::DEBUG, "Episode %s, %d options", c->what, c->showings.size());
			for (const auto & i : c->showings) {
				if (selected.find(i) != selected.end()) {
					logger->messagebf(LOG::DEBUG, "	%s - %s (%d) <-", i->startTime, i->stopTime, i->transportStreamId);
				}
				else if (i) {
					logger->messagebf(LOG::DEBUG, "	%s - %s (%d)", i->startTime, i->stopTime, i->transportStreamId);
				}
			}
		}
		logger->message(LOG::DEBUG, "----------");
		for (const auto & c : group) {
			bool found = false;
			for (const auto & i : c->showings) {
				if (i && selected.find(i) != selected.end()) {
					found = true;
					break;
				}
			}
			for (const auto & i : c->showings) {
				if (i) {
					records.push_back(new P2PVR::ScheduledToRecord(i->eventUid,
									found ?
									selected.find(i) != selected.end() ? P2PVR::WillRecordThisShowing : P2PVR::WillRecordOtherShowing :
									P2PVR::CannotRecordAnyShowing, i->scheduleId));
				}
			}
		}
	}

	auto dbc = db->get();
	DB::TransactionScope tx(dbc.get());
	DB::TablePatch mergeRecords;
	mergeRecords.dest = "record";
	Slicer::SerializeAny<Slicer::SqlTablePatchSerializer>(records, dbc.get(), mergeRecords);

	auto recorder = P2PVR::RecorderPrx::checkedCast(ice.adapter->createProxy(ice.adapter->getCommunicator()->stringToIdentity("Recorder")));
	recorder->RefreshSchedules();
}

void
SchedulesI::DeleteSchedule(int id, const Ice::Current & ice)
{
	auto dbc = db->get();
	auto del = P2PVR::sql::schedules::deleteById.modify(dbc.get());
	del->bindParamI(0, id);
	del->execute();
	DoReschedule(ice);
}

P2PVR::ScheduleList
SchedulesI::GetSchedules(const Ice::Current &)
{
	logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
	return fetch<P2PVR::ScheduleList>(P2PVR::sql::schedules::selectAll);
}

P2PVR::SchedulePtr
SchedulesI::GetSchedule(int id, const Ice::Current &)
{
	logger->messagebf(LOG::DEBUG, "%s(%d)", __PRETTY_FUNCTION__, id);
	auto schedules = fetch<P2PVR::ScheduleList>(P2PVR::sql::schedules::selectById, id);
	if (schedules.empty()) throw P2PVR::NotFound();
	return schedules.front();
}

P2PVR::ScheduledToRecordList
SchedulesI::GetScheduledToRecord(const Ice::Current &)
{
	logger->message(LOG::DEBUG, __PRETTY_FUNCTION__);
	return fetch<P2PVR::ScheduledToRecordList>(P2PVR::sql::schedules::scheduledToRecord);
}

Ice::Int
SchedulesI::NewSchedule(const P2PVR::SchedulePtr & s, const Ice::Current & ice)
{
	auto dbc = db->get();
	Slicer::SerializeAny<Slicer::SqlFetchIdInsertSerializer>(s, dbc.get(), "schedules");
	DoReschedule(ice);
	return s->ScheduleId;
}

void
SchedulesI::UpdateSchedule(const P2PVR::SchedulePtr & s, const Ice::Current & ice)
{
	auto dbc = db->get();
	Slicer::SerializeAny<Slicer::SqlUpdateSerializer>(s, dbc.get(), "schedules");
	DoReschedule(ice);
}
}

INSTANTIATEFACTORY(P2PVR::EpisodeGroup, const P2PVR::Episodes &);