1 /******************************************************************************
2 * Copyright (c) 2018, Texas Instruments Incorporated - http://www.ti.com/
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of Texas Instruments Incorporated nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26 * THE POSSIBILITY OF SUCH DAMAGE.
27 *****************************************************************************/
28 #include <signal.h>
29 #include <getopt.h>
30 #include <iostream>
31 #include <iomanip>
32 #include <fstream>
33 #include <cassert>
34 #include <string>
35 #include <functional>
36 #include <algorithm>
37 #include <time.h>
38 #include <unistd.h>
40 #include <queue>
41 #include <vector>
42 #include <cstdio>
44 #include "executor.h"
45 #include "execution_object.h"
46 #include "configuration.h"
47 #include "../segmentation/object_classes.h"
49 #include "opencv2/core.hpp"
50 #include "opencv2/imgproc.hpp"
51 #include "opencv2/highgui.hpp"
52 #include "opencv2/videoio.hpp"
54 #define NUM_VIDEO_FRAMES 100
55 #define DEFAULT_CONFIG "jdetnet"
56 #define DEFAULT_INPUT "../test/testvecs/input/preproc_0_768x320.y"
58 bool __TI_show_debug_ = false;
59 bool is_default_input = false;
60 bool is_preprocessed_input = false;
61 bool is_camera_input = false;
62 int orig_width;
63 int orig_height;
64 object_class_table_t *object_class_table;
66 using namespace tidl;
67 using namespace cv;
70 bool RunConfiguration(const std::string& config_file, uint32_t num_devices,
71 DeviceType device_type, std::string& input_file);
72 bool ReadFrame(ExecutionObject& eo, int frame_idx,
73 const Configuration& configuration, int num_frames,
74 std::string& image_file, VideoCapture &cap);
75 bool WriteFrameOutput(const ExecutionObject &eo_in,
76 const ExecutionObject &eo_out,
77 const Configuration& configuration);
79 void ReportTime(int frame_index, std::string device_name, double elapsed_host,
80 double elapsed_device);
82 static void ProcessArgs(int argc, char *argv[],
83 std::string& config,
84 uint32_t& num_devices,
85 DeviceType& device_type,
86 std::string& input_file);
88 static void DisplayHelp();
90 static double ms_diff(struct timespec &t0, struct timespec &t1)
91 { return (t1.tv_sec - t0.tv_sec) * 1e3 + (t1.tv_nsec - t0.tv_nsec) / 1e6; }
94 int main(int argc, char *argv[])
95 {
96 // Catch ctrl-c to ensure a clean exit
97 signal(SIGABRT, exit);
98 signal(SIGTERM, exit);
100 // If there are no devices capable of offloading TIDL on the SoC, exit
101 uint32_t num_dla = Executor::GetNumDevices(DeviceType::DLA);
102 uint32_t num_dsp = Executor::GetNumDevices(DeviceType::DSP);
103 if (num_dla == 0 || num_dsp == 0)
104 {
105 std::cout << "ssd_multibox requires both DLA and DSP for execution."
106 << std::endl;
107 return EXIT_SUCCESS;
108 }
110 // Process arguments
111 std::string config = DEFAULT_CONFIG;
112 std::string input_file = DEFAULT_INPUT;
113 uint32_t num_devices = 1;
114 DeviceType device_type = DeviceType::DLA;
115 ProcessArgs(argc, argv, config, num_devices, device_type, input_file);
117 // Use same number of DLAs and DSPs
118 num_devices = std::min(num_devices, std::min(num_dla, num_dsp));
119 if (num_devices == 0)
120 {
121 std::cout << "Partitioned execution requires at least 1 DLA and 1 DSP."
122 << std::endl;
123 return EXIT_FAILURE;
124 }
125 if ((object_class_table = GetObjectClassTable(config)) == nullptr)
126 {
127 std::cout << "No object classes defined for this config." << std::endl;
128 return EXIT_FAILURE;
129 }
131 if (input_file == DEFAULT_INPUT) is_default_input = true;
132 if (input_file == "camera") is_camera_input = true;
133 if (input_file.length() > 2 &&
134 input_file.compare(input_file.length() - 2, 2, ".y") == 0)
135 is_preprocessed_input = true;
136 std::cout << "Input: " << input_file << std::endl;
137 std::string config_file = "../test/testvecs/config/infer/tidl_config_"
138 + config + ".txt";
139 bool status = RunConfiguration(config_file, num_devices, device_type,
140 input_file);
142 if (!status)
143 {
144 std::cout << "ssd_multibox FAILED" << std::endl;
145 return EXIT_FAILURE;
146 }
148 std::cout << "ssd_multibox PASSED" << std::endl;
149 return EXIT_SUCCESS;
150 }
152 bool RunConfiguration(const std::string& config_file, uint32_t num_devices,
153 DeviceType device_type, std::string& input_file)
154 {
155 DeviceIds ids;
156 for (int i = 0; i < num_devices; i++)
157 ids.insert(static_cast<DeviceId>(i));
159 // Read the TI DL configuration file
160 Configuration configuration;
161 bool status = configuration.ReadFromFile(config_file);
162 if (!status)
163 {
164 std::cerr << "Error in configuration file: " << config_file
165 << std::endl;
166 return false;
167 }
169 // setup input
170 int num_frames = is_default_input ? 3 : 1;
171 VideoCapture cap;
172 std::string image_file;
173 if (is_camera_input)
174 {
175 cap = VideoCapture(1); // cap = VideoCapture("test.mp4");
176 if (! cap.isOpened())
177 {
178 std::cerr << "Cannot open camera input." << std::endl;
179 return false;
180 }
181 num_frames = NUM_VIDEO_FRAMES;
182 namedWindow("SSD_Multibox", WINDOW_AUTOSIZE | CV_GUI_NORMAL);
183 }
184 else
185 {
186 image_file = input_file;
187 }
189 try
190 {
191 // Create a executor with the approriate core type, number of cores
192 // and configuration specified
193 // DLA will run layersGroupId 1 in the network, while
194 // DSP will run layersGroupId 2 in the network
195 Executor executor_dla(DeviceType::DLA, ids, configuration, 1);
196 Executor executor_dsp(DeviceType::DSP, ids, configuration, 2);
198 // Query Executor for set of ExecutionObjects created
199 const ExecutionObjects& execution_objects_dla =
200 executor_dla.GetExecutionObjects();
201 const ExecutionObjects& execution_objects_dsp =
202 executor_dsp.GetExecutionObjects();
203 int num_eos = execution_objects_dla.size();
205 // Allocate input and output buffers for each execution object
206 // Note that "out" is both the output of eo_dla and the input of eo_dsp
207 // This is how two layersGroupIds, 1 and 2, are tied together
208 std::vector<void *> buffers;
209 for (int i = 0; i < num_eos; i++)
210 {
211 ExecutionObject *eo_dla = execution_objects_dla[i].get();
212 size_t in_size = eo_dla->GetInputBufferSizeInBytes();
213 size_t out_size = eo_dla->GetOutputBufferSizeInBytes();
214 ArgInfo in = { ArgInfo(malloc(in_size), in_size) };
215 ArgInfo out = { ArgInfo(malloc(out_size), out_size) };
216 eo_dla->SetInputOutputBuffer(in, out);
218 ExecutionObject *eo_dsp = execution_objects_dsp[i].get();
219 size_t out2_size = eo_dsp->GetOutputBufferSizeInBytes();
220 ArgInfo out2 = { ArgInfo(malloc(out2_size), out2_size) };
221 eo_dsp->SetInputOutputBuffer(out, out2);
223 buffers.push_back(in.ptr());
224 buffers.push_back(out.ptr());
225 buffers.push_back(out2.ptr());
226 }
228 #define MAX_NUM_EOS 4
229 struct timespec t0[MAX_NUM_EOS], t1, tloop0, tloop1;
230 clock_gettime(CLOCK_MONOTONIC, &tloop0);
232 // Process frames with available execution objects in a pipelined manner
233 // additional num_eos iterations to flush the pipeline (epilogue)
234 ExecutionObject *eo_dla, *eo_dsp, *eo_input;
235 for (int frame_idx = 0;
236 frame_idx < num_frames + num_eos; frame_idx++)
237 {
238 eo_dla = execution_objects_dla[frame_idx % num_eos].get();
239 eo_dsp = execution_objects_dsp[frame_idx % num_eos].get();
241 // Wait for previous frame on the same eo to finish processing
242 if (eo_dsp->ProcessFrameWait())
243 {
244 int finished_idx = eo_dsp->GetFrameIndex();
245 clock_gettime(CLOCK_MONOTONIC, &t1);
246 ReportTime(finished_idx, "DSP",
247 ms_diff(t0[finished_idx % num_eos], t1),
248 eo_dsp->GetProcessTimeInMilliSeconds());
250 eo_input = execution_objects_dla[finished_idx % num_eos].get();
251 WriteFrameOutput(*eo_input, *eo_dsp, configuration);
252 }
254 // Read a frame and start processing it with current eo
255 if (ReadFrame(*eo_dla, frame_idx, configuration, num_frames,
256 image_file, cap))
257 {
258 clock_gettime(CLOCK_MONOTONIC, &t0[frame_idx % num_eos]);
259 eo_dla->ProcessFrameStartAsync();
261 if (eo_dla->ProcessFrameWait())
262 {
263 clock_gettime(CLOCK_MONOTONIC, &t1);
264 ReportTime(frame_idx, "DLA",
265 ms_diff(t0[frame_idx % num_eos], t1),
266 eo_dla->GetProcessTimeInMilliSeconds());
268 clock_gettime(CLOCK_MONOTONIC, &t0[frame_idx % num_eos]);
269 eo_dsp->ProcessFrameStartAsync();
270 }
271 }
272 }
274 clock_gettime(CLOCK_MONOTONIC, &tloop1);
275 std::cout << "Loop total time (including read/write/print/etc): "
276 << std::setw(6) << std::setprecision(4)
277 << ms_diff(tloop0, tloop1) << "ms" << std::endl;
279 for (auto b : buffers)
280 free(b);
281 }
282 catch (tidl::Exception &e)
283 {
284 std::cerr << e.what() << std::endl;
285 status = false;
286 }
288 return status;
289 }
291 void ReportTime(int frame_index, std::string device_name, double elapsed_host,
292 double elapsed_device)
293 {
294 double overhead = 100 - (elapsed_device/elapsed_host*100);
295 std::cout << "frame[" << frame_index << "]: "
296 << "Time on " << device_name << ": "
297 << std::setw(6) << std::setprecision(4)
298 << elapsed_device << "ms, "
299 << "host: "
300 << std::setw(6) << std::setprecision(4)
301 << elapsed_host << "ms ";
302 std::cout << "API overhead: "
303 << std::setw(6) << std::setprecision(3)
304 << overhead << " %" << std::endl;
305 }
308 bool ReadFrame(ExecutionObject &eo, int frame_idx,
309 const Configuration& configuration, int num_frames,
310 std::string& image_file, VideoCapture &cap)
311 {
312 if (frame_idx >= num_frames)
313 return false;
314 eo.SetFrameIndex(frame_idx);
316 char* frame_buffer = eo.GetInputBufferPtr();
317 assert (frame_buffer != nullptr);
318 int channel_size = configuration.inWidth * configuration.inHeight;
320 Mat image;
321 if (! image_file.empty())
322 {
323 if (is_preprocessed_input)
324 {
325 std::ifstream ifs(image_file, std::ios::binary);
326 ifs.seekg(frame_idx * channel_size * 3);
327 ifs.read(frame_buffer, channel_size * 3);
328 bool ifs_status = ifs.good();
329 ifs.close();
330 orig_width = configuration.inWidth;
331 orig_height = configuration.inHeight;
332 return ifs_status; // already PreProc-ed
333 }
334 else
335 {
336 image = cv::imread(image_file, CV_LOAD_IMAGE_COLOR);
337 if (image.empty())
338 {
339 std::cerr << "Unable to read from: " << image_file << std::endl;
340 return false;
341 }
342 }
343 }
344 else
345 {
346 // 640x480 camera input, process one in every 5 frames,
347 // can adjust number of skipped frames to match real time processing
348 if (! cap.grab()) return false;
349 if (! cap.grab()) return false;
350 if (! cap.grab()) return false;
351 if (! cap.grab()) return false;
352 if (! cap.grab()) return false;
353 if (! cap.retrieve(image)) return false;
354 }
356 // scale to network input size
357 Mat s_image, bgr_frames[3];
358 orig_width = image.cols;
359 orig_height = image.rows;
360 cv::resize(image, s_image,
361 Size(configuration.inWidth, configuration.inHeight),
362 0, 0, cv::INTER_AREA);
363 cv::split(s_image, bgr_frames);
364 memcpy(frame_buffer, bgr_frames[0].ptr(), channel_size);
365 memcpy(frame_buffer+1*channel_size, bgr_frames[1].ptr(), channel_size);
366 memcpy(frame_buffer+2*channel_size, bgr_frames[2].ptr(), channel_size);
367 return true;
368 }
370 // Create frame with boxes drawn around classified objects
371 bool WriteFrameOutput(const ExecutionObject &eo_in,
372 const ExecutionObject &eo_out,
373 const Configuration& configuration)
374 {
375 // Asseembly original frame
376 int width = configuration.inWidth;
377 int height = configuration.inHeight;
378 int channel_size = width * height;
379 Mat frame, r_frame, bgr[3];
381 unsigned char *in = (unsigned char *) eo_in.GetInputBufferPtr();
382 bgr[0] = Mat(height, width, CV_8UC(1), in);
383 bgr[1] = Mat(height, width, CV_8UC(1), in + channel_size);
384 bgr[2] = Mat(height, width, CV_8UC(1), in + channel_size*2);
385 cv::merge(bgr, 3, frame);
387 int frame_index = eo_in.GetFrameIndex();
388 char outfile_name[64];
389 if (! is_camera_input && is_preprocessed_input)
390 {
391 snprintf(outfile_name, 64, "frame_%d.png", frame_index);
392 cv::imwrite(outfile_name, frame);
393 printf("Saving frame %d to: %s\n", frame_index, outfile_name);
394 }
396 // Draw boxes around classified objects
397 float *out = (float *) eo_out.GetOutputBufferPtr();
398 int num_floats = eo_out.GetOutputBufferSizeInBytes() / sizeof(float);
399 for (int i = 0; i < num_floats / 7; i++)
400 {
401 int index = (int) out[i * 7 + 0];
402 if (index < 0) break;
404 int label = (int) out[i * 7 + 1];
405 float score = out[i * 7 + 2];
406 int xmin = (int) (out[i * 7 + 3] * width);
407 int ymin = (int) (out[i * 7 + 4] * height);
408 int xmax = (int) (out[i * 7 + 5] * width);
409 int ymax = (int) (out[i * 7 + 6] * height);
411 object_class_t *object_class = GetObjectClass(object_class_table,
412 label);
413 if (object_class == nullptr) continue;
415 #if 0
416 printf("(%d, %d) -> (%d, %d): %s, score=%f\n",
417 xmin, ymin, xmax, ymax, object_class->label, score);
418 #endif
420 cv::rectangle(frame, Point(xmin, ymin), Point(xmax, ymax),
421 Scalar(object_class->color.blue,
422 object_class->color.green,
423 object_class->color.red), 2);
424 }
426 // output
427 cv::resize(frame, r_frame, Size(orig_width, orig_height));
428 if (is_camera_input)
429 {
430 cv::imshow("SSD_Multibox", r_frame);
431 waitKey(1);
432 }
433 else
434 {
435 snprintf(outfile_name, 64, "multibox_%d.png", frame_index);
436 cv::imwrite(outfile_name, r_frame);
437 printf("Saving frame %d with SSD multiboxes to: %s\n",
438 frame_index, outfile_name);
439 }
441 return true;
442 }
445 void ProcessArgs(int argc, char *argv[], std::string& config,
446 uint32_t& num_devices, DeviceType& device_type,
447 std::string& input_file)
448 {
449 const struct option long_options[] =
450 {
451 {"config", required_argument, 0, 'c'},
452 {"num_devices", required_argument, 0, 'n'},
453 {"image_file", required_argument, 0, 'i'},
454 {"help", no_argument, 0, 'h'},
455 {"verbose", no_argument, 0, 'v'},
456 {0, 0, 0, 0}
457 };
459 int option_index = 0;
461 while (true)
462 {
463 int c = getopt_long(argc, argv, "c:n:i:hv", long_options, &option_index);
465 if (c == -1)
466 break;
468 switch (c)
469 {
470 case 'c': config = optarg;
471 break;
473 case 'n': num_devices = atoi(optarg);
474 assert (num_devices > 0 && num_devices <= 4);
475 break;
477 case 'i': input_file = optarg;
478 break;
480 case 'v': __TI_show_debug_ = true;
481 break;
483 case 'h': DisplayHelp();
484 exit(EXIT_SUCCESS);
485 break;
487 case '?': // Error in getopt_long
488 exit(EXIT_FAILURE);
489 break;
491 default:
492 std::cerr << "Unsupported option: " << c << std::endl;
493 break;
494 }
495 }
496 }
498 void DisplayHelp()
499 {
500 std::cout << "Usage: ssd_multibox\n"
501 " Will run partitioned ssd_multibox network to perform "
502 "multi-objects detection\n"
503 " and classification. First part of network "
504 "(layersGroupId 1) runs on DLA,\n"
505 " second part (layersGroupId 2) runs on DSP.\n"
506 " Use -c to run a different segmentation network. "
507 "Default is jdetnet.\n"
508 "Optional arguments:\n"
509 " -c <config> Valid configs: jdetnet \n"
510 " -n <number of cores> Number of cores to use (1 - 4)\n"
511 " -i <image> Path to the image file\n"
512 " Default is 1 frame in testvecs\n"
513 " -i camera Use camera as input\n"
514 " -v Verbose output during execution\n"
515 " -h Help\n";
516 }