Пример #1
0
Файл: hw_disk.c Проект: 5kg/gdb
static void
hw_disk_init_address(device *me)
{
  hw_disk_device *disk = device_data(me);
  unsigned_word address;
  int space;
  const char *name;

  /* attach to the parent. Since the bus is logical, attach using just
     the unit-address (size must be zero) */
  device_address_to_attach_address(device_parent(me), device_unit_address(me),
				   &space, &address, me);
  device_attach_address(device_parent(me), attach_callback,
			space, address, 0/*size*/, access_read_write_exec,
			me);

  /* Tell the world we are a disk.  */
  device_add_string_property(me, "device_type", "block");

  /* get the name of the file specifying the disk image */
  disk->name_index = 0;
  disk->nr_names = device_find_string_array_property(me, "file",
						     disk->name_index, &name);
  if (!disk->nr_names)
    device_error(me, "invalid file property");

  /* is it a RO device? */
  disk->read_only =
    (strcmp(device_name(me), "disk") != 0
     && strcmp(device_name(me), "floppy") != 0
     && device_find_property(me, "read-only") == NULL);

  /* now open it */
  open_disk_image(me, disk, name);
}
    std::pair<std::string, std::string> default_device_names()
    {
        const PaDeviceIndex default_input = Pa_GetDefaultInputDevice();
        const PaDeviceIndex default_output = Pa_GetDefaultOutputDevice();

        std::cout << default_input << " " << default_output;

        return std::make_pair(device_name(default_input), device_name(default_output));
    }
Пример #3
0
/*-------------------------------------------------------------------------
 * Function : API_DeviceId
 *            get the device identification (ID) for the current device.
 * Input    : *pars_p, *result_sym_p
 * Output   :
 * Return   : TRUE if ok, else FALSE
 * ----------------------------------------------------------------------*/
static BOOL API_DeviceId( STTST_Parse_t *pars_p, char *result_sym_p )
{
    BOOL RetErr = FALSE;
#ifdef ST_OS20
    device_id_t devid;
#endif /* ST_OS20 */
    UNUSED_PARAMETER(pars_p);
    UNUSED_PARAMETER(result_sym_p);

#ifdef ST_OSLINUX
    sprintf(API_Msg, "Device Id not available\n\n");
#else
#ifdef ST_OS20
    devid = device_id();
    sprintf(API_Msg, "Device 0x%x (%s)\n\n", devid.id, device_name(devid));
#endif /* ST_OS20 */

#ifdef ST_OS21
    sprintf(API_Msg, "Device (%s)\n\n", kernel_chip());
#endif /* ST_OS21 */

#endif
    STTBX_Print(( API_Msg ));
    return ( API_EnableError ? RetErr : FALSE );
} /* end of API_DeviceId */
Пример #4
0
void music_init()
  {
  char *path;
/*  if (sound_detection)
     {
     SEND_LOG("(SOUND) SOUND_DETECT Detecting sound card",0,0);
     if (sound_detect(&snd_devnum,&snd_parm1,&snd_parm2,&snd_parm3)) snd_devnum=DEV_NOSOUND;
     }*/
  SEND_LOG("(SOUND) SOUND_SET Setting Sound: Device '%s' Port: %3X",device_name(snd_devnum),snd_parm1);
  SEND_LOG("(SOUND) SOUND_SET Setting Sound: IRQ: %X DMA: %X",snd_parm2,snd_parm3);
  set_mixing_device(snd_devnum,snd_mixing,snd_parm1,snd_parm2,snd_parm3);
  SEND_LOG("(SOUND) SOUND_INIT Starting mixing",0,0);
  start_mixing();
  set_snd_effect(SND_GFX,init_gfx_vol);
  set_snd_effect(SND_MUSIC,init_music_vol);
  path=plugins_path;
  if (path==0 || path[0]==0)  
    path=AutodetectWinAmp();
  if (path!=0 && path[0]!=0)
  {
    SEND_LOG("(SOUND) Installing plugins, path: %s",path,0);
    init_winamp_plugins(path);
    if (path!=plugins_path) free(path);
  }  
  SEND_LOG("(SOUND) SOUND_DONE Sound Engine should work now",0,0);

  }
Пример #5
0
  MemDisk::MemDisk() noexcept
  : Block_device(),
    image_start_ { &_DISK_START_ },
    image_end_   { &_DISK_END_ },

    stat_read( Statman::get().create(
               Stat::UINT64, device_name() + ".reads").get_uint64() )
  {
    INFO("Memdisk", "Initializing");
  }
Пример #6
0
static uint8_t
get_id_from_device(device_t dev)
{
	char devname[10];

	device_name(dev, devname);
	if (devname[3] == 'c')
		return 0xff;

	/* device name should be net[0-9] */
	return (devname[3] - '0');
}
Пример #7
0
void CUDAAccel::print_cuda_devices(void) {
  if (getenv("VMDCUDANODISPLAYGPUS")) {
    msgInfo << "Ignoring CUDA-capable GPUs used for display" << sendmsg;
  }

  if (!cudaavail || numdevices == 0) {
    msgInfo << "No CUDA accelerator devices available." << sendmsg;
    return;
  }

  msgInfo << "Detected " << numdevices << " available CUDA " 
          << ((numdevices > 1) ? "accelerators:" : "accelerator:") << sendmsg;
  int i;
  for (i=0; i<numdevices; i++) {
    char outstr[1024];
    memset(outstr, 0, sizeof(outstr));

    // list primary GPU device attributes
    sprintf(outstr, "[%d] %-18s %2d SM_%d.%d @ %.2f GHz",
            device_index(i), device_name(i), 
            (device_sm_count(i) > 0) ? device_sm_count(i) : 0,
            device_version_major(i), device_version_minor(i),
            device_clock_ghz(i));
    msgInfo << outstr;

    // list memory capacity 
    int gpumemmb = (device_membytes(i) / (1024 * 1024));
    if (gpumemmb < 1000)
      sprintf(outstr, ", %4dMB RAM", gpumemmb);
    else if (gpumemmb < 10240)
      sprintf(outstr, ", %.1fGB RAM", gpumemmb / 1024.0);
    else 
      sprintf(outstr, ", %dGB RAM", gpumemmb / 1024);

    msgInfo << outstr;

    // list optional hardware features and configuration attributes here...
    if (device_computemode(i) == computeModeProhibited) {
      msgInfo << ", Compute Mode: Prohibited";
    } else {
      if (device_kerneltimeoutenabled(i))
        msgInfo << ", KTO";

      if (device_overlap(i))
        msgInfo << ", OIO";

      if (device_canmaphostmem(i))
        msgInfo << ", ZCP";
    }

    msgInfo << sendmsg; 
  } 
}
Пример #8
0
void
ActionLog::apply_action_xFun(sqlite3_context* context, int argc, sqlite3_value** argv)
{
  ActionLog* the = reinterpret_cast<ActionLog*>(sqlite3_user_data(context));

  if (argc != 11) {
    sqlite3_result_error(context, "``apply_action'' expects 10 arguments", -1);
    return;
  }

  Buffer device_name(sqlite3_value_blob(argv[0]), sqlite3_value_bytes(argv[0]));
  sqlite3_int64 seq_no = sqlite3_value_int64(argv[1]);
  int action = sqlite3_value_int(argv[2]);
  std::string filename = reinterpret_cast<const char*>(sqlite3_value_text(argv[3]));
  sqlite3_int64 version = sqlite3_value_int64(argv[4]);

  _LOG_TRACE("apply_function called with " << argc);
  _LOG_TRACE("device_name: " << Name(Block(reinterpret_cast<const char*>(device_name.buf()),
                                           device_name.size()))
                             << ", action: "
                             << action
                             << ", file: "
                             << filename);

  if (action == 0) // update
  {
    Buffer hash(sqlite3_value_blob(argv[5]), sqlite3_value_bytes(argv[5]));
    time_t atime = static_cast<time_t>(sqlite3_value_int64(argv[6]));
    time_t mtime = static_cast<time_t>(sqlite3_value_int64(argv[7]));
    time_t ctime = static_cast<time_t>(sqlite3_value_int64(argv[8]));
    int mode = sqlite3_value_int(argv[9]);
    int seg_num = sqlite3_value_int(argv[10]);

    _LOG_DEBUG("Update " << filename << " " << atime << " " << mtime << " " << ctime << " "
                         << toHex(hash));

    the->m_fileState->UpdateFile(filename, version, hash, device_name, seq_no, atime, mtime, ctime,
                                 mode, seg_num);

    // no callback here
  }
  else if (action == 1) // delete
  {
    the->m_fileState->DeleteFile(filename);

    the->m_onFileRemoved(filename);
  }

  sqlite3_result_null(context);
}
Пример #9
0
std::unique_ptr<std::wstring> rawinput_device_name(HANDLE hDevice){
	UINT _data_size;
    UINT _result;
	if(0 != GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, 0, &_data_size)){
		std::cerr << "rawinput_device_name: 0 != GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, 0, &data_size)" << std::endl;
		return std::unique_ptr<std::wstring>(nullptr);
	}

    std::unique_ptr<std::wstring> device_name (new std::wstring(_data_size, '\0'));
    _result = GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, &(*device_name)[0], &_data_size);
    if(-1 == _result){
		std::cerr << "rawinput_device_name: -1 == GetRawInputDeviceInfoW(hDevice, RIDI_DEVICENAME, &(*device_name)[0], &data_size)" << std::endl;
		return std::unique_ptr<std::wstring>(nullptr);
	}

    device_name->resize(_result);
	return device_name;
}
Пример #10
0
    bool match_device (std::string const & device, int & r_device_index)
    {
        if (device.empty())
            return true;

        int device_number = Pa_GetDeviceCount();
        if (device_number < 0) {
            report_error(device_number);
            return false;
        }

        for (int i = 0; i != device_number; ++i) {
            if (device_name(i) == device) {
                r_device_index = i;
                return true;
            }
        }
        return false;
    }
Пример #11
0
Файл: hw_disk.c Проект: 5kg/gdb
static void
open_disk_image(device *me,
		hw_disk_device *disk,
		const char *name)
{
  if (disk->image != NULL)
    fclose(disk->image);
  if (disk->name != NULL)
    free(disk->name);
  disk->name = strdup(name);
  disk->image = fopen(disk->name, disk->read_only ? "r" : "r+");
  if (disk->image == NULL) {
    perror(device_name(me));
    device_error(me, "open %s failed\n", disk->name);
  }

  DTRACE(disk, ("image %s (%s)\n",
                disk->name,
                (disk->read_only ? "read-only" : "read-write")));
}
Пример #12
0
static int
hw_stack_ioctl(device *me,
	       cpu *processor,
	       unsigned_word cia,
	       device_ioctl_request request,
	       va_list ap)
{
  switch (request) {
  case device_ioctl_create_stack:
    {
      unsigned_word stack_pointer = va_arg(ap, unsigned_word);
      char **argv = va_arg(ap, char **);
      char **envp = va_arg(ap, char **);
      const char *stack_type;
      DTRACE(stack,
	     ("stack_ioctl_callback(me=0x%lx:%s processor=0x%lx cia=0x%lx argv=0x%lx envp=0x%lx)\n",
	      (long)me, device_name(me),
	      (long)processor,
	      (long)cia,
	      (long)argv,
	      (long)envp));
      stack_type = device_find_string_property(me, "stack-type");
      if (strcmp(stack_type, "ppc-elf") == 0)
	create_ppc_elf_stack_frame(me, stack_pointer, argv, envp);
      else if (strcmp(stack_type, "ppc-xcoff") == 0)
	create_ppc_aix_stack_frame(me, stack_pointer, argv, envp);
      else if (strcmp(stack_type, "chirp") == 0)
	create_ppc_chirp_bootargs(me, argv);
      else if (strcmp(stack_type, "none") != 0)
	device_error(me, "Unknown initial stack frame type %s", stack_type);
      DTRACE(stack, 
	     ("stack_ioctl_callback() = void\n"));
      break;
    }
  default:
    device_error(me, "Unsupported ioctl requested");
    break;
  }
  return 0;
}
Пример #13
0
static void
write_stack_arguments(device *me,
		      char **arg,
		      unsigned_word start_block,
		      unsigned_word end_block,
		      unsigned_word start_arg,
		      unsigned_word end_arg)
{
  DTRACE(stack,
	("write_stack_arguments(device=%s, arg=0x%lx, start_block=0x%lx, end_block=0x%lx, start_arg=0x%lx, end_arg=0x%lx)\n",
	 device_name(me), (long)arg, (long)start_block, (long)end_block, (long)start_arg, (long)end_arg));
  if (arg == NULL)
    device_error(me, "Attempt to write a null array onto the stack\n");
  /* only copy in arguments, memory is already zero */
  for (; *arg != NULL; arg++) {
    int len = strlen(*arg)+1;
    unsigned_word target_start_block;
    DTRACE(stack,
	  ("write_stack_arguments() write %s=%s at %s=0x%lx %s=0x%lx %s=0x%lx\n",
	   "**arg", *arg, "start_block", (long)start_block,
	   "len", (long)len, "start_arg", (long)start_arg));
    if (psim_write_memory(device_system(me), 0, *arg,
			  start_block, len,
			  0/*violate_readonly*/) != len)
      device_error(me, "Write of **arg (%s) at 0x%lx of stack failed\n",
		   *arg, (unsigned long)start_block);
    target_start_block = H2T_word(start_block);
    if (psim_write_memory(device_system(me), 0, &target_start_block,
			  start_arg, sizeof(target_start_block),
			  0) != sizeof(target_start_block))
      device_error(me, "Write of *arg onto stack failed\n");
    start_block += ALIGN_8(len);
    start_arg += sizeof(start_block);
  }
  start_arg += sizeof(start_block); /*the null at the end*/
  if (start_block != end_block
      || ALIGN_8(start_arg) != end_arg)
    device_error(me, "Probable corrpution of stack arguments\n");
  DTRACE(stack, ("write_stack_arguments() = void\n"));
}
Пример #14
0
int main(int argc, char* argv[])
#endif
{
  try
  {
#if defined(WIN32)
    std::locale console_locale("Russian_Russia.866");
    std::wcout.imbue(console_locale);
    std::wcerr.imbue(console_locale);
    std::locale sys_locale("");
#endif

    if (2 > argc || 4 < argc)
    {
      print_usage();
      return EXIT_FAILURE;
    }

    std::size_t cpu_count = boost::thread::hardware_concurrency();
    std::size_t concurrent_count = 2 > cpu_count ? 2 : cpu_count;
    std::size_t thread_count = 2;

    std::cout << "Number of found CPUs             : "
              << cpu_count << std::endl
              << "Number of concurrent work threads: "
              << concurrent_count << std::endl
              << "Total number of work threads     : "
              << thread_count << std::endl;

#if defined(WIN32)
    std::wstring wide_device_name(argv[1]);
    const wcodecvt_type& wcodecvt(std::use_facet<wcodecvt_type>(sys_locale));
    std::string device_name(ma::codecvt_cast::out(wide_device_name, wcodecvt));
#else
    std::string device_name(argv[1]);
#endif

    std::size_t read_buffer_size =
        std::max<std::size_t>(1024, session::min_read_buffer_size);
    std::size_t message_queue_size =
        std::max<std::size_t>(64, session::min_message_queue_size);

    if (argc > 2)
    {
      try
      {
        read_buffer_size = boost::lexical_cast<std::size_t>(argv[2]);
        if (3 < argc)
        {
          message_queue_size = boost::lexical_cast<std::size_t>(argv[3]);
        }
      }
      catch (const boost::bad_lexical_cast& e)
      {
        std::cerr << L"Invalid parameter value/format: "
            << e.what() << std::endl;
        print_usage();
        return EXIT_FAILURE;
      }
      catch (const std::exception& e)
      {
        std::cerr << "Unexpected error during parameters parsing: "
            << e.what() << std::endl;
        print_usage();
        return EXIT_FAILURE;
      }
    } // if (argc > 2)

#if defined(WIN32)
    std::wcout << L"NMEA 0183 device serial port: "
               << wide_device_name << std::endl
               << L"Read buffer size (bytes)    : "
               << read_buffer_size << std::endl
               << L"Read buffer size (messages) : "
               << message_queue_size << std::endl;
#else
    std::cout << "NMEA 0183 device serial port: "
              << device_name << std::endl
              << "Read buffer size (bytes)    : "
              << read_buffer_size << std::endl
              << "Read buffer size (messages) : "
              << message_queue_size << std::endl;
#endif // defined(WIN32)

    handler_allocator_type the_allocator;

    frame_buffer_ptr the_frame_buffer(
        boost::make_shared<frame_buffer_type>(message_queue_size));

    // An io_service for the thread pool
    // (for the executors... Java Executors API? Apache MINA :)
    boost::asio::io_service session_io_service(concurrent_count);

    session_ptr the_session(session::create(session_io_service,
        read_buffer_size, message_queue_size, "$", "\x0a"));

    // Prepare the lower layer - open the serial port
    boost::system::error_code error;
    the_session->serial_port().open(device_name, error);
    if (error)
    {
#if defined(WIN32)
      std::wstring error_message =
          ma::codecvt_cast::in(error.message(), wcodecvt);
      std::wcerr << L"Failed to open serial port: "
          << error_message << std::endl;
#else
      std::cerr << "Failed to open serial port: "
          << error.message() << std::endl;
#endif // defined(WIN32)
      return EXIT_FAILURE;
    }

    // Start session (not actually, because there are no work threads yet)
    the_session->async_start(ma::make_custom_alloc_handler(the_allocator,
        boost::bind(handle_start, the_session, boost::ref(the_allocator),
            the_frame_buffer, _1)));

    // Setup console controller
    ma::console_controller console_controller(
        boost::bind(handle_console_close, the_session));

    std::cout << "Press Ctrl+C (Ctrl+Break) to exit...\n";

    // Create work threads
    boost::thread_group work_threads;
    for (std::size_t i = 0; i != thread_count; ++i)
    {
      work_threads.create_thread(
          boost::bind(&boost::asio::io_service::run, &session_io_service));
    }
    work_threads.join_all();

    std::cout << "Work threads are stopped.\n";
    return EXIT_SUCCESS;
  }
  catch (const std::exception& e)
  {
    std::cerr << "Unexpected error: " << e.what() << std::endl;
  }
  catch (...)
  {
    std::cerr << "Unknown exception" << std::endl;
  }
  return EXIT_FAILURE;
}
Пример #15
0
static int add_swap(const char *what, struct mntent *me) {
        _cleanup_free_ char *name = NULL, *unit = NULL, *lnk = NULL, *device = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        bool noauto, nofail;
        int r, pri = -1;

        assert(what);
        assert(me);

        r = mount_find_pri(me, &pri);
        if (r < 0) {
                log_error("Failed to parse priority");
                return pri;
        }

        noauto = !!hasmntopt(me, "noauto");
        nofail = !!hasmntopt(me, "nofail");

        name = unit_name_from_path(what, ".swap");
        if (!name)
                return log_oom();

        unit = strjoin(arg_dest, "/", name, NULL);
        if (!unit)
                return log_oom();

        f = fopen(unit, "wxe");
        if (!f) {
                if (errno == EEXIST)
                        log_error("Failed to create swap unit file %s, as it already exists. Duplicate entry in /etc/fstab?", unit);
                else
                        log_error("Failed to create unit file %s: %m", unit);
                return -errno;
        }

        fputs("# Automatically generated by systemd-fstab-generator\n\n"
              "[Unit]\n"
              "SourcePath=/etc/fstab\n"
              "DefaultDependencies=no\n"
              "Conflicts=" SPECIAL_UMOUNT_TARGET "\n"
              "Before=" SPECIAL_UMOUNT_TARGET "\n", f);

        if (!noauto && !nofail)
                fputs("Before=" SPECIAL_SWAP_TARGET "\n", f);

        fprintf(f,
                "\n"
                "[Swap]\n"
                "What=%s\n",
                what);

        if (pri >= 0)
                fprintf(f,
                        "Priority=%i\n",
                        pri);

        fflush(f);
        if (ferror(f)) {
                log_error("Failed to write unit file %s: %m", unit);
                return -errno;
        }

        if (!noauto) {
                lnk = strjoin(arg_dest, "/" SPECIAL_SWAP_TARGET ".wants/", name, NULL);
                if (!lnk)
                        return log_oom();

                mkdir_parents_label(lnk, 0755);
                if (symlink(unit, lnk) < 0) {
                        log_error("Failed to create symlink %s: %m", lnk);
                        return -errno;
                }

                r = device_name(what, &device);
                if (r < 0)
                        return r;

                if (r > 0) {
                        free(lnk);
                        lnk = strjoin(arg_dest, "/", device, ".wants/", name, NULL);
                        if (!lnk)
                                return log_oom();

                        mkdir_parents_label(lnk, 0755);
                        if (symlink(unit, lnk) < 0) {
                                log_error("Failed to create symlink %s: %m", lnk);
                                return -errno;
                        }
                }
        }

        return 0;
}
Пример #16
0
static int add_mount(
                const char *what,
                const char *where,
                const char *type,
                const char *opts,
                int passno,
                bool noauto,
                bool nofail,
                bool automount,
                bool isbind,
                const char *pre,
                const char *pre2,
                const char *online,
                const char *post,
                const char *source) {
        _cleanup_free_ char
                *name = NULL, *unit = NULL, *lnk = NULL, *device = NULL,
                *automount_name = NULL, *automount_unit = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        int r;

        assert(what);
        assert(where);
        assert(type);
        assert(opts);
        assert(source);

        if (streq(type, "autofs"))
                return 0;

        if (!is_path(where)) {
                log_warning("Mount point %s is not a valid path, ignoring.", where);
                return 0;
        }

        if (mount_point_is_api(where) ||
            mount_point_ignore(where))
                return 0;

        name = unit_name_from_path(where, ".mount");
        if (!name)
                return log_oom();

        unit = strjoin(arg_dest, "/", name, NULL);
        if (!unit)
                return log_oom();

        f = fopen(unit, "wxe");
        if (!f) {
                if (errno == EEXIST)
                        log_error("Failed to create mount unit file %s, as it already exists. Duplicate entry in /etc/fstab?", unit);
                else
                        log_error("Failed to create unit file %s: %m", unit);
                return -errno;
        }

        fprintf(f,
              "# Automatically generated by systemd-fstab-generator\n\n"
              "[Unit]\n"
              "SourcePath=%s\n"
              "DefaultDependencies=no\n",
              source);

        if (!path_equal(where, "/")) {
                if (pre)
                        fprintf(f,
                                "After=%s\n",
                                pre);

                if (pre2)
                        fprintf(f,
                                "After=%s\n",
                                pre2);

                if (online)
                        fprintf(f,
                                "After=%s\n"
                                "Wants=%s\n",
                                online,
                                online);

                fprintf(f,
                        "Conflicts=" SPECIAL_UMOUNT_TARGET "\n"
                        "Before=" SPECIAL_UMOUNT_TARGET "\n");
        }

        if (post && !noauto && !nofail && !automount)
                fprintf(f,
                        "Before=%s\n",
                        post);

        fprintf(f,
                "\n"
                "[Mount]\n"
                "What=%s\n"
                "Where=%s\n"
                "Type=%s\n"
                "FsckPassNo=%i\n",
                what,
                where,
                type,
                passno);

        if (!isempty(opts) &&
            !streq(opts, "defaults"))
                fprintf(f,
                        "Options=%s\n",
                        opts);

        fflush(f);
        if (ferror(f)) {
                log_error("Failed to write unit file %s: %m", unit);
                return -errno;
        }

        if (!noauto) {
                /* don't start network mounts automatically, we do that via ifupdown hooks for now */
                if (post && !streq(post, SPECIAL_REMOTE_FS_TARGET)) {
                        lnk = strjoin(arg_dest, "/", post, nofail || automount ? ".wants/" : ".requires/", name, NULL);
                        if (!lnk)
                                return log_oom();

                        mkdir_parents_label(lnk, 0755);
                        if (symlink(unit, lnk) < 0) {
                                log_error("Failed to create symlink %s: %m", lnk);
                                return -errno;
                        }
                }

                if (!isbind &&
                    !path_equal(where, "/")) {

                        r = device_name(what, &device);
                        if (r < 0)
                                return r;

                        if (r > 0) {
                                free(lnk);
                                lnk = strjoin(arg_dest, "/", device, ".wants/", name, NULL);
                                if (!lnk)
                                        return log_oom();

                                mkdir_parents_label(lnk, 0755);
                                if (symlink(unit, lnk) < 0) {
                                        log_error("Failed to create symlink %s: %m", lnk);
                                        return -errno;
                                }
                        }
                }
        }

        if (automount && !path_equal(where, "/")) {
                automount_name = unit_name_from_path(where, ".automount");
                if (!name)
                        return log_oom();

                automount_unit = strjoin(arg_dest, "/", automount_name, NULL);
                if (!automount_unit)
                        return log_oom();

                fclose(f);
                f = fopen(automount_unit, "wxe");
                if (!f) {
                        log_error("Failed to create unit file %s: %m", automount_unit);
                        return -errno;
                }

                fprintf(f,
                        "# Automatically generated by systemd-fstab-generator\n\n"
                        "[Unit]\n"
                        "SourcePath=%s\n"
                        "DefaultDependencies=no\n"
                        "Conflicts=" SPECIAL_UMOUNT_TARGET "\n"
                        "Before=" SPECIAL_UMOUNT_TARGET "\n",
                        source);

                if (post)
                        fprintf(f,
                                "Before= %s\n",
                                post);

                fprintf(f,
                        "[Automount]\n"
                        "Where=%s\n",
                        where);

                fflush(f);
                if (ferror(f)) {
                        log_error("Failed to write unit file %s: %m", automount_unit);
                        return -errno;
                }

                free(lnk);
                lnk = strjoin(arg_dest, "/", post, nofail ? ".wants/" : ".requires/", automount_name, NULL);
                if (!lnk)
                        return log_oom();

                mkdir_parents_label(lnk, 0755);
                if (symlink(automount_unit, lnk) < 0) {
                        log_error("Failed to create symlink %s: %m", lnk);
                        return -errno;
                }
        }

        return 0;
}
Пример #17
0
/**
 * Constructor which create the GStreamer pipeline.
 * This pipeline grabs the video and render the OpenGL.
 */
Pipeline::Pipeline(Application* owner) :
        owner_(owner), 
        record_all_frames_enabled_(false)
{
    Configuration *config = owner_->get_configuration();
    bool verbose = config->get_verbose();
    set_intervalometer_is_on(false);
    pipeline_ = NULL;
    pipeline_ = GST_PIPELINE(gst_pipeline_new("pipeline"));

    GstElement* dv_demux0 = NULL;
    GstElement* hdv_decoder0 = NULL;
    GstElement* dv_videoscale0 = NULL;
    GstElement* dv_ffmpegcolorspace = NULL;
    GstElement* dvdec = NULL;
    GstElement* dv_queue0 = NULL;
    //GstElement* dv_queue1 = NULL;
    // capsfilter0, for the capture FPS and size
    GstElement* capsfilter0 = gst_element_factory_make ("capsfilter", NULL);

    bool is_dv_enabled = config->videoSource() == "dv";
    bool is_hdv_enabled = config->videoSource() == "hdv";
    // Video source element
    // TODO: add more input types like in Ekiga
    if (verbose)
        std::cout << "Video source: " << config->videoSource() << std::endl;
    if (config->videoSource() == "test")
    {
        videosrc_  = gst_element_factory_make("videotestsrc", "videosrc0");
    } 
    else if (config->videoSource() == "x") 
    {
        videosrc_  = gst_element_factory_make("ximagesrc", "videosrc0");
    } 
    else if (config->videoSource() == "dv") 
    {
        if (! Raw1394::cameraIsReady())
            g_error("There is no DV camera that is ready.");
        videosrc_  = gst_element_factory_make("dv1394src", "videosrc0");
        dv_demux0 = gst_element_factory_make("dvdemux", "dv_demux0");
        dv_queue0  = gst_element_factory_make("queue", "dv_queue0");
        dvdec = gst_element_factory_make("dvdec", "dvdec");
        dv_videoscale0 = gst_element_factory_make("videoscale", "dv_videoscale0");
        dv_ffmpegcolorspace = gst_element_factory_make("ffmpegcolorspace", "dv_ffmpegcolorspace");
        //dv_queue1  = gst_element_factory_make("queue", "dv_queue1");
        // register connection callback for the dvdemux element.
        // Note that the demuxer will be linked to whatever after it dynamically.
        // The reason is that the DV may contain various streams (for example
        // audio and video). The source pad(s) will be created at run time,
        // by the demuxer when it detects the amount and nature of streams.
        // Therefore we connect a callback function which will be executed
        // when the "pad-added" is emitted.
        g_signal_connect(dv_demux0, "pad-added",
            G_CALLBACK(cb_new_dvdemux_src_pad),
            static_cast<gpointer>(dv_queue0));
        //g_assert(dv_demux0);
    } 
    else if (config->videoSource() == "hdv") 
    {
        videosrc_  = gst_element_factory_make("hdv1394src", "videosrc0");
        hdv_decoder0 = gst_element_factory_make("decodebin", "hdv_decoder0");
        g_assert(hdv_decoder0);
    } 
    else  // v4l2src
    {
        // TODO:2010-08-06:aalex:We could rely on gstreamer-properties to configure the video source.
        // Add -d gconf (gconfvideosrc)
        std::string device_name(config->videoSource());
        if (verbose)
        {
            std::cout << "Video source: v4l2src with camera " << device_name << std::endl;
        }
        videosrc_  = gst_element_factory_make("v4l2src", "videosrc0"); 
        g_object_set(videosrc_, "device", device_name.c_str(), NULL); 
    }
    // TODO: use something else than g_assert to see if we could create the elements.
    g_assert(videosrc_); 

    // ffmpegcolorspace0 element
    GstElement* ffmpegcolorspace0 = gst_element_factory_make("ffmpegcolorspace", "ffmpegcolorspace0");
    g_assert(ffmpegcolorspace0);
    GstElement* tee0 = gst_element_factory_make("tee", "tee0");
    g_assert(tee0);
    GstElement* queue0 = gst_element_factory_make("queue", "queue0");
    g_assert(queue0);

    videosink_ = gst_element_factory_make ("cluttersink", NULL);
    g_object_set (videosink_, "texture", CLUTTER_TEXTURE(owner_->get_gui()->get_live_input_texture()), NULL);

    // TODO: Make sure the rendering FPS is constant, and not subordinate to
    // the FPS of the camera.

    // GdkPixbuf sink:
    GstElement* queue1 = gst_element_factory_make("queue", "queue1");
    g_assert(queue1);
    gdkpixbufsink_ = gst_element_factory_make("gdkpixbufsink", "gdkpixbufsink0");
    g_assert(gdkpixbufsink_);

    bool is_preview_enabled = config->get_preview_window_enabled();
    GstElement *queue2 = NULL;
    GstElement *ffmpegcolorspace1 = NULL;
    GstElement *xvimagesink = NULL;
    if (is_preview_enabled)
    {
        queue2 = gst_element_factory_make("queue", "queue2");
        g_assert(queue2);
        ffmpegcolorspace1 = gst_element_factory_make("ffmpegcolorspace", "ffmpegcolorspace1");
        g_assert(ffmpegcolorspace1);
        xvimagesink = gst_element_factory_make("xvimagesink", "xvimagesink0");
        g_assert(xvimagesink);
        g_object_set(xvimagesink, "force-aspect-ratio", TRUE, NULL);
    }

    // add elements
    gst_bin_add(GST_BIN(pipeline_), videosrc_); // capture
    gst_bin_add(GST_BIN(pipeline_), capsfilter0);
    if (is_dv_enabled)
    {
        gst_bin_add(GST_BIN(pipeline_), dv_demux0);
        gst_bin_add(GST_BIN(pipeline_), dv_queue0);
        gst_bin_add(GST_BIN(pipeline_), dvdec);
        gst_bin_add(GST_BIN(pipeline_), dv_ffmpegcolorspace);
        gst_bin_add(GST_BIN(pipeline_), dv_videoscale0);
        //gst_bin_add(GST_BIN(pipeline_), dv_queue1);
        // Set the capsfilter caps for DV:
    } 
    else if (is_hdv_enabled)
    {
        gst_bin_add(GST_BIN(pipeline_), hdv_decoder0);
    }
    gst_bin_add(GST_BIN(pipeline_), ffmpegcolorspace0);
    gst_bin_add(GST_BIN(pipeline_), tee0);
    gst_bin_add(GST_BIN(pipeline_), queue0); // branch #0: videosink
    //gst_bin_add(GST_BIN(pipeline_), capsfilter1);
    gst_bin_add(GST_BIN(pipeline_), videosink_);
    gst_bin_add(GST_BIN(pipeline_), queue1); // branch #1: gdkpixbufsink
    gst_bin_add(GST_BIN(pipeline_), gdkpixbufsink_);
    if (is_preview_enabled)
    {
        gst_bin_add(GST_BIN(pipeline_), queue2); // branch #2: xvimagesink
        gst_bin_add(GST_BIN(pipeline_), ffmpegcolorspace1);
        gst_bin_add(GST_BIN(pipeline_), xvimagesink);
    }

    // link pads:
    gboolean is_linked = FALSE; 
    if (config->videoSource() == std::string("test") || config->videoSource() == std::string("x")) 
    {
        if (config->videoSource() == std::string("x")) 
        {
            g_object_set(G_OBJECT(videosrc_), "endx", config->get_capture_width(), NULL);
            g_object_set(G_OBJECT(videosrc_), "endy", config->get_capture_height(), NULL);
            GstCaps *the_caps = gst_caps_from_string("video/x-raw-rgb, framerate=30/1");
            g_object_set(capsfilter0, "caps", the_caps, NULL);
            gst_caps_unref(the_caps);
            
        }
        else
        {   // it's a videotestsrc
            std::string caps_str = "video/x-raw-yuv, width=" + boost::lexical_cast<std::string>(config->get_capture_width()) + ", height=" + boost::lexical_cast<std::string>(config->get_capture_height()) + ", framerate=30/1";
            std::cout << "CAPS: " << caps_str << std::endl;
            GstCaps *the_caps = gst_caps_from_string(caps_str.c_str());
            g_object_set(capsfilter0, "caps", the_caps, NULL);
            gst_caps_unref(the_caps);
        }

        link_or_die(videosrc_, capsfilter0);
    } 
    else if (is_dv_enabled || is_hdv_enabled) 
    {
        if (is_dv_enabled)
        {
            link_or_die(videosrc_, dv_demux0);
            // dv_demux0 is linked to dvdec when its src pads appear
            link_or_die(dv_queue0, dvdec);
            link_or_die(dvdec, dv_ffmpegcolorspace);
            link_or_die(dv_ffmpegcolorspace, dv_videoscale0);
            link_or_die(dv_videoscale0, capsfilter0);
        } 
        else // hdv
        {
            g_error("HDV is not yet implemented."); // quits
        }
    } 
    else // it's a v4l2src
    {     
        bool source_is_linked = false;
        int frame_rate_index = 0;
        // Guess the right FPS to use with the video capture device
        while (not source_is_linked)
        {
            GstCaps *videocaps = gst_caps_from_string(guess_source_caps(frame_rate_index).c_str());
            g_object_set(capsfilter0, "caps", videocaps, NULL);
            gst_caps_unref(videocaps);
            is_linked = gst_element_link(videosrc_, capsfilter0);
            if (!is_linked) 
            { 
                std::cout << "Failed to link video source. Trying another framerate." << std::endl;
                ++frame_rate_index;
            }
            else 
            {
                if (verbose)
                    std::cout << "Success." << std::endl;
                source_is_linked = true;
            }
        }
    }
    //Will now link capfilter0--ffmpegcolorspace0--tee.
    link_or_die(capsfilter0, ffmpegcolorspace0);
    link_or_die(ffmpegcolorspace0, tee0);
    //Will now link tee--queue--videosink.
    is_linked = gst_element_link_pads(tee0, "src0", queue0, "sink");
    if (!is_linked) 
    {
        g_print("Could not link %s to %s.\n", "tee0", "sink"); 
        exit(1);
    }
    // output 0: the OpenGL uploader.
    link_or_die(queue0, videosink_);

    // output 1: the GdkPixbuf sink
    //Will now link tee--queue--pixbufsink.
    is_linked = gst_element_link_pads(tee0, "src1", queue1, "sink");
    if (!is_linked) 
    { 
        g_print("Could not link %s to %s.\n", "tee0", "queue1"); 
        exit(1); 
    }
    link_or_die(queue1, gdkpixbufsink_);

    if (is_preview_enabled)
    {
        
        is_linked = gst_element_link_pads(tee0, "src2", queue2, "sink");
        if (!is_linked) 
        { 
            g_print("Could not link %s to %s.\n", "tee0", "queue2"); 
            exit(1); 
        }
       
        is_linked = gst_element_link(queue2, ffmpegcolorspace1);
        if (!is_linked) 
        { 
            g_print("Could not link %s to %s.\n", "queue2", "ffmpegcolorspace1"); 
            exit(1); 
        }
        is_linked = gst_element_link(ffmpegcolorspace1, xvimagesink);
        if (!is_linked) 
        { 
            g_print("Could not link %s to %s.\n", "ffmpegcolorspace1", "xvimagesink0"); 
            exit(1); 
        }
    }

    if (verbose)
        std::cout << "Will now setup the pipeline bus." << std::endl;
    /* setup bus */
    GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline_));
    gst_bus_add_signal_watch(bus);
    g_signal_connect(bus, "message::error", G_CALLBACK(end_stream_cb), this);
    g_signal_connect(bus, "message::warning", G_CALLBACK(end_stream_cb), this);
    g_signal_connect(bus, "message::eos", G_CALLBACK(end_stream_cb), this);
    g_signal_connect(bus, "message", G_CALLBACK(bus_message_cb), this);
    gst_object_unref(bus);

    /* run */
    GstStateChangeReturn ret;
    if (verbose)
        std::cout << "Set pipeline to READY" << std::endl;
    ret = gst_element_set_state(GST_ELEMENT(pipeline_), GST_STATE_READY);
    if (ret == GST_STATE_CHANGE_FAILURE)
    {
        g_print("Failed to make the video pipeline ready!\n");
    }
    if (verbose)
        std::cout << "Set pipeline to PLAYING" << std::endl;
    ret = gst_element_set_state(GST_ELEMENT(pipeline_), GST_STATE_PLAYING);
    if (ret == GST_STATE_CHANGE_FAILURE)
    {
        g_print("Failed to start the video pipeline!\n");
        g_print("-----------------------------------\n");
        /* check if there is an error message with details on the bus */
        GstMessage* msg = gst_bus_poll(bus, GST_MESSAGE_ERROR, 0);
        if (msg)
        {
          GError *err = NULL;
          gst_message_parse_error(msg, &err, NULL);
          g_print("ERROR: %s\n", err->message);
          g_error_free(err);
          gst_message_unref(msg);
        }
        g_print("-----------------------------------\n");
        exit(1);
        //FIXME: causes a segfault: context->owner_->quit();
    }
    if (verbose)
        std::cout << "Successfully started the pipeline." << std::endl;
}
Пример #18
0
int main(int argc, char *argv[])
{
    struct stat buf = { 0 };
    struct mntent *mnt = NULL;
    FILE *fp = NULL;
    gchar *uri;
    gint fileindex = 1;
    GError *error = NULL;
    GOptionContext *context;
    gint i;
    gdouble volume = 100.0;
    gchar *accelerator_keys;
    gchar **parse;
#ifdef GTK3_ENABLED
    GtkSettings *gtk_settings;
#endif
    int stat_result;

#ifndef OS_WIN32
    struct sigaction sa;
#endif
    gboolean playiter = FALSE;

#ifdef GIO_ENABLED
    GFile *file;
#endif

#ifdef ENABLE_NLS
    bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
    bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
    textdomain(GETTEXT_PACKAGE);
#endif

    playlist = 0;
    embed_window = 0;
    control_id = 0;
    window_x = 0;
    window_y = 0;
    last_window_width = 0;
    last_window_height = 0;
    showcontrols = 1;
    showsubtitles = TRUE;
    autostart = 1;
    videopresent = 0;
    disable_context_menu = FALSE;
    dontplaynext = FALSE;
    idledata = (IdleData *) g_new0(IdleData, 1);
    idledata->videopresent = FALSE;
    idledata->length = 0.0;
    idledata->device = NULL;
    idledata->cachepercent = -1.0;
    selection = NULL;
    path = NULL;
    js_state = STATE_UNDEFINED;
    control_instance = TRUE;
    playlistname = NULL;
    rpconsole = NULL;
    subtitle = NULL;
    tv_device = NULL;
    tv_driver = NULL;
    tv_width = 0;
    tv_height = 0;
    tv_fps = 0;
    ok_to_play = TRUE;
    alang = NULL;
    slang = NULL;
    metadata_codepage = NULL;
    playlistname = NULL;
    window_width = -1;
    window_height = -1;
    stored_window_width = -1;
    stored_window_height = -1;
    cache_size = 0;
    forcecache = FALSE;
    use_volume_option = FALSE;
    vertical_layout = FALSE;
    playlist_visible = FALSE;
    disable_fullscreen = FALSE;
    disable_framedrop = FALSE;
    softvol = FALSE;
    remember_softvol = FALSE;
    volume_softvol = -1;
    volume_gain = 0;
    subtitlefont = NULL;
    subtitle_codepage = NULL;
    subtitle_color = NULL;
    subtitle_outline = FALSE;
    subtitle_shadow = FALSE;
    subtitle_fuzziness = 0;
    disable_embeddedfonts = FALSE;
    quit_on_complete = FALSE;
    verbose = 0;
    reallyverbose = 0;
    embedding_disabled = FALSE;
    disable_pause_on_click = FALSE;
    disable_animation = FALSE;
    auto_hide_timeout = 3;
    mouse_over_controls = FALSE;
    use_mediakeys = TRUE;
    use_defaultpl = FALSE;
    mplayer_bin = NULL;
    mplayer_dvd_device = NULL;
    single_instance = FALSE;
    disable_deinterlace = TRUE;
    details_visible = FALSE;
    replace_and_play = FALSE;
    bring_to_front = FALSE;
    keep_on_top = FALSE;
    resize_on_new_media = FALSE;
    use_pausing_keep_force = FALSE;
    show_notification = TRUE;
    show_status_icon = TRUE;
    lang_group = NULL;
    audio_group = NULL;
    gpod_mount_point = NULL;
    load_tracks_from_gpod = FALSE;
    disable_cover_art_fetch = FALSE;
    fullscreen = 0;
    vo = NULL;
    data = NULL;
    max_data = NULL;
    details_table = NULL;
    large_buttons = FALSE;
    button_size = GTK_ICON_SIZE_BUTTON;
    lastguistate = -1;
    non_fs_height = 0;
    non_fs_width = 0;
    use_hw_audio = FALSE;
    start_second = 0;
    play_length = 0;
    save_loc = TRUE;
    use_xscrnsaver = FALSE;
    screensaver_disabled = FALSE;
    update_control_flag = FALSE;
    gchar *filename;
    skip_fixed_allocation_on_show = FALSE;
    skip_fixed_allocation_on_hide = FALSE;
    pref_volume = -1;
    use_mplayer2 = FALSE;
    enable_global_menu = FALSE;

#ifndef OS_WIN32
    sa.sa_handler = hup_handler;
    sigemptyset(&sa.sa_mask);
#ifdef SA_RESTART
    sa.sa_flags = SA_RESTART;   /* Restart functions if
                                   interrupted by handler */
#endif
#ifdef SIGINT
    if (sigaction(SIGINT, &sa, NULL) == -1)
        printf("SIGINT signal handler not installed\n");
#endif
#ifdef SIGHUP
    if (sigaction(SIGHUP, &sa, NULL) == -1)
        printf("SIGHUP signal handler not installed\n");
#endif
#ifdef SIGTERM
    if (sigaction(SIGTERM, &sa, NULL) == -1)
        printf("SIGTERM signal handler not installed\n");
#endif
#endif

    // call g_type_init or otherwise we can crash
    gtk_init(&argc, &argv);
    if (!g_thread_supported())
        g_thread_init(NULL);

    uri = g_strdup_printf("%s/gnome-mplayer/cover_art", g_get_user_config_dir());
    if (!g_file_test(uri, G_FILE_TEST_IS_DIR)) {
        g_mkdir_with_parents(uri, 0775);
    }
    g_free(uri);

    uri = g_strdup_printf("%s/gnome-mplayer/plugin", g_get_user_config_dir());
    if (!g_file_test(uri, G_FILE_TEST_IS_DIR)) {
        g_mkdir_with_parents(uri, 0775);
    }
    g_free(uri);
    uri = NULL;

    default_playlist = g_strdup_printf("file://%s/gnome-mplayer/default.pls", g_get_user_config_dir());
    safe_to_save_default_playlist = TRUE;

    gm_store = gm_pref_store_new("gnome-mplayer");
    gmp_store = gm_pref_store_new("gecko-mediaplayer");
    vo = gm_pref_store_get_string(gm_store, VO);
    audio_device.alsa_mixer = gm_pref_store_get_string(gm_store, ALSA_MIXER);
    use_hardware_codecs = gm_pref_store_get_boolean(gm_store, USE_HARDWARE_CODECS);
    use_crystalhd_codecs = gm_pref_store_get_boolean(gm_store, USE_CRYSTALHD_CODECS);
    osdlevel = gm_pref_store_get_int(gm_store, OSDLEVEL);
    pplevel = gm_pref_store_get_int(gm_store, PPLEVEL);
#ifndef HAVE_ASOUNDLIB
    volume = gm_pref_store_get_int(gm_store, VOLUME);
#endif
    audio_channels = gm_pref_store_get_int(gm_store, AUDIO_CHANNELS);
    use_hw_audio = gm_pref_store_get_boolean(gm_store, USE_HW_AUDIO);
    fullscreen = gm_pref_store_get_boolean(gm_store, FULLSCREEN);
    softvol = gm_pref_store_get_boolean(gm_store, SOFTVOL);
    remember_softvol = gm_pref_store_get_boolean(gm_store, REMEMBER_SOFTVOL);
    volume_softvol = gm_pref_store_get_float(gm_store, VOLUME_SOFTVOL);
    volume_gain = gm_pref_store_get_int(gm_store, VOLUME_GAIN);
    forcecache = gm_pref_store_get_boolean(gm_store, FORCECACHE);
    vertical_layout = gm_pref_store_get_boolean(gm_store, VERTICAL);
    playlist_visible = gm_pref_store_get_boolean(gm_store, SHOWPLAYLIST);
    details_visible = gm_pref_store_get_boolean(gm_store, SHOWDETAILS);
    show_notification = gm_pref_store_get_boolean(gm_store, SHOW_NOTIFICATION);
    show_status_icon = gm_pref_store_get_boolean(gm_store, SHOW_STATUS_ICON);
    showcontrols = gm_pref_store_get_boolean_with_default(gm_store, SHOW_CONTROLS, showcontrols);
    restore_controls = showcontrols;
    disable_deinterlace = gm_pref_store_get_boolean(gm_store, DISABLEDEINTERLACE);
    disable_framedrop = gm_pref_store_get_boolean(gm_store, DISABLEFRAMEDROP);
    disable_fullscreen = gm_pref_store_get_boolean(gm_store, DISABLEFULLSCREEN);
    disable_context_menu = gm_pref_store_get_boolean(gm_store, DISABLECONTEXTMENU);
    disable_ass = gm_pref_store_get_boolean(gm_store, DISABLEASS);
    disable_embeddedfonts = gm_pref_store_get_boolean(gm_store, DISABLEEMBEDDEDFONTS);
    disable_pause_on_click = gm_pref_store_get_boolean(gm_store, DISABLEPAUSEONCLICK);
    disable_animation = gm_pref_store_get_boolean(gm_store, DISABLEANIMATION);
    auto_hide_timeout = gm_pref_store_get_int_with_default(gm_store, AUTOHIDETIMEOUT, auto_hide_timeout);
    disable_cover_art_fetch = gm_pref_store_get_boolean(gm_store, DISABLE_COVER_ART_FETCH);
    use_mediakeys = gm_pref_store_get_boolean_with_default(gm_store, USE_MEDIAKEYS, use_mediakeys);
    use_defaultpl = gm_pref_store_get_boolean_with_default(gm_store, USE_DEFAULTPL, use_defaultpl);
    metadata_codepage = gm_pref_store_get_string(gm_store, METADATACODEPAGE);

    alang = gm_pref_store_get_string(gm_store, AUDIO_LANG);
    slang = gm_pref_store_get_string(gm_store, SUBTITLE_LANG);

    subtitlefont = gm_pref_store_get_string(gm_store, SUBTITLEFONT);
    subtitle_scale = gm_pref_store_get_float(gm_store, SUBTITLESCALE);
    if (subtitle_scale < 0.25) {
        subtitle_scale = 1.0;
    }
    subtitle_codepage = gm_pref_store_get_string(gm_store, SUBTITLECODEPAGE);
    subtitle_color = gm_pref_store_get_string(gm_store, SUBTITLECOLOR);
    subtitle_outline = gm_pref_store_get_boolean(gm_store, SUBTITLEOUTLINE);
    subtitle_shadow = gm_pref_store_get_boolean(gm_store, SUBTITLESHADOW);
    subtitle_margin = gm_pref_store_get_int(gm_store, SUBTITLE_MARGIN);
    subtitle_fuzziness = gm_pref_store_get_int(gm_store, SUBTITLE_FUZZINESS);
    showsubtitles = gm_pref_store_get_boolean_with_default(gm_store, SHOW_SUBTITLES, TRUE);

    qt_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_QT);
    real_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_REAL);
    wmp_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_WMP);
    dvx_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_DVX);
    midi_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_MIDI);
    embedding_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_EMBEDDING);
    disable_embedded_scaling = gm_pref_store_get_boolean(gmp_store, DISABLE_EMBEDDED_SCALING);
    if (embed_window == 0) {
        single_instance = gm_pref_store_get_boolean(gm_store, SINGLE_INSTANCE);
        if (single_instance) {
            replace_and_play = gm_pref_store_get_boolean(gm_store, REPLACE_AND_PLAY);
            bring_to_front = gm_pref_store_get_boolean(gm_store, BRING_TO_FRONT);
        }
    }
    enable_global_menu = gm_pref_store_get_boolean(gm_store, ENABLE_GLOBAL_MENU);
    if (!enable_global_menu) {
        enable_global_menu = (g_getenv("UBUNTU_MENUPROXY") == NULL ? FALSE : TRUE);
    }

    enable_nautilus_plugin = gm_pref_store_get_boolean_with_default(gm_store, ENABLE_NAUTILUS_PLUGIN, TRUE);

    mplayer_bin = gm_pref_store_get_string(gm_store, MPLAYER_BIN);
    if (mplayer_bin != NULL && !g_file_test(mplayer_bin, G_FILE_TEST_EXISTS)) {
        g_free(mplayer_bin);
        mplayer_bin = NULL;
    }
    mplayer_dvd_device = gm_pref_store_get_string(gm_store, MPLAYER_DVD_DEVICE);
    extraopts = gm_pref_store_get_string(gm_store, EXTRAOPTS);
    use_xscrnsaver = gm_pref_store_get_boolean_with_default(gm_store, USE_XSCRNSAVER, use_xscrnsaver);

    accelerator_keys = gm_pref_store_get_string(gm_store, ACCELERATOR_KEYS);
    accel_keys = g_strv_new(KEY_COUNT);
    accel_keys_description = g_strv_new(KEY_COUNT);
    if (accelerator_keys != NULL) {
        parse = g_strsplit(accelerator_keys, " ", KEY_COUNT);
        for (i = 0; i < g_strv_length(parse); i++) {
            accel_keys[i] = g_strdup(parse[i]);
        }
        g_free(accelerator_keys);
        g_strfreev(parse);
    }
    assign_default_keys();
    accel_keys_description[FILE_OPEN_LOCATION] = g_strdup(_("Open Location"));
    accel_keys_description[EDIT_SCREENSHOT] = g_strdup(_("Take Screenshot"));
    accel_keys_description[EDIT_PREFERENCES] = g_strdup(_("Preferences"));
    accel_keys_description[VIEW_PLAYLIST] = g_strdup(_("Playlist"));
    accel_keys_description[VIEW_INFO] = g_strdup(_("Media Info"));
    accel_keys_description[VIEW_DETAILS] = g_strdup(_("Details"));
    accel_keys_description[VIEW_METER] = g_strdup(_("Audio Meter"));
    accel_keys_description[VIEW_FULLSCREEN] = g_strdup(_("Full Screen"));
    accel_keys_description[VIEW_ASPECT] = g_strdup(_("Aspect"));
    accel_keys_description[VIEW_SUBTITLES] = g_strdup(_("Subtitles"));
    accel_keys_description[VIEW_DECREASE_SIZE] = g_strdup(_("Decrease Subtitle Size"));
    accel_keys_description[VIEW_INCREASE_SIZE] = g_strdup(_("Increase Subtitle Size"));
    accel_keys_description[VIEW_ANGLE] = g_strdup(_("Switch Angle"));
    accel_keys_description[VIEW_CONTROLS] = g_strdup(_("Controls"));

    remember_loc = gm_pref_store_get_boolean(gm_store, REMEMBER_LOC);
    loc_window_x = gm_pref_store_get_int(gm_store, WINDOW_X);
    loc_window_y = gm_pref_store_get_int(gm_store, WINDOW_Y);
    loc_window_height = gm_pref_store_get_int(gm_store, WINDOW_HEIGHT);
    loc_window_width = gm_pref_store_get_int(gm_store, WINDOW_WIDTH);
    loc_panel_position = gm_pref_store_get_int(gm_store, PANEL_POSITION);

    keep_on_top = gm_pref_store_get_boolean(gm_store, KEEP_ON_TOP);
    resize_on_new_media = gm_pref_store_get_boolean(gm_store, RESIZE_ON_NEW_MEDIA);
    mouse_wheel_changes_volume = gm_pref_store_get_boolean_with_default(gm_store, MOUSE_WHEEL_CHANGES_VOLUME, FALSE);

    audio_device_name = gm_pref_store_get_string(gm_store, AUDIO_DEVICE_NAME);
    audio_device.description = g_strdup(audio_device_name);

    context = g_option_context_new(_("[FILES...] - GNOME Media player based on MPlayer"));
#ifdef GTK2_12_ENABLED
    g_option_context_set_translation_domain(context, "UTF-8");
    g_option_context_set_translate_func(context, (GTranslateFunc) gettext, NULL, NULL);
#endif
    g_option_context_add_main_entries(context, entries, GETTEXT_PACKAGE);
    g_option_context_add_group(context, gtk_get_option_group(TRUE));
    g_option_context_parse(context, &argc, &argv, &error);
    g_option_context_free(context);

    if (new_instance)
        single_instance = FALSE;

    if (verbose == 0)
        verbose = gm_pref_store_get_int(gm_store, VERBOSE);

    if (reallyverbose)
        verbose = 2;

    if (verbose) {
        printf(_("GNOME MPlayer v%s\n"), VERSION);
        printf(_("gmtk v%s\n"), gmtk_version());
    }

    if (cache_size == 0)
        cache_size = gm_pref_store_get_int(gm_store, CACHE_SIZE);
    if (cache_size == 0)
        cache_size = 2000;

    plugin_audio_cache_size = gm_pref_store_get_int(gm_store, PLUGIN_AUDIO_CACHE_SIZE);
    if (plugin_audio_cache_size == 0)
        plugin_audio_cache_size = 2000;

    plugin_video_cache_size = gm_pref_store_get_int(gm_store, PLUGIN_VIDEO_CACHE_SIZE);
    if (plugin_video_cache_size == 0)
        plugin_video_cache_size = 2000;

    if (control_id != 0)
        cache_size = plugin_video_cache_size;

    gm_pref_store_free(gm_store);
    gm_pref_store_free(gmp_store);

    if (verbose && embed_window) {
        printf("embedded in window id 0x%x\n", embed_window);
    }

    if (verbose && single_instance) {
        printf("Running in single instance mode\n");
    }
#ifdef GIO_ENABLED
    if (verbose) {
        printf("Running with GIO support\n");
    }
#endif
#ifdef ENABLE_PANSCAN
    if (verbose) {
        printf("Running with panscan enabled (mplayer svn r29565 or higher required)\n");
    }
#endif
    if (verbose) {
        printf("Using audio device: %s\n", audio_device_name);
    }

    if (softvol) {
        if (verbose)
            printf("Using MPlayer Software Volume control\n");
        if (remember_softvol && volume_softvol != -1) {
            if (verbose)
                printf("Using last volume of %f%%\n", volume_softvol * 100.0);
            volume = (gdouble) volume_softvol *100.0;
        } else {
            volume = 100.0;
        }
    }

    if (large_buttons)
        button_size = GTK_ICON_SIZE_DIALOG;

    if (playlist_visible && control_id != 0)
        playlist_visible = FALSE;

    if (error != NULL) {
        printf("%s\n", error->message);
        printf(_("Run 'gnome-mplayer --help' to see a full list of available command line options.\n"));
        return 1;
    }
    // if (verbose)
    //      printf("Threading support enabled = %i\n",g_thread_supported());

    if (rpconsole == NULL)
        rpconsole = g_strdup("NONE");

    // setup playliststore
    playliststore =
        gtk_list_store_new(N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT,
                           G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_FLOAT, G_TYPE_STRING,
                           G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_STRING, G_TYPE_STRING,
                           G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT, G_TYPE_INT, G_TYPE_INT,
                           G_TYPE_FLOAT, G_TYPE_FLOAT, G_TYPE_BOOLEAN);

    // only use dark theme if not embedded, otherwise use the default theme  
#ifdef GTK3_ENABLED
    if (embed_window <= 0) {
        gtk_settings = gtk_settings_get_default();
        g_object_set(G_OBJECT(gtk_settings), "gtk-application-prefer-dark-theme", TRUE, NULL);
    }
#endif

    create_window(embed_window);

    autopause = FALSE;
#ifdef GIO_ENABLED
    idledata->caching = g_mutex_new();
    idledata->caching_complete = g_cond_new();
#endif

    retrieve_metadata_pool = g_thread_pool_new(retrieve_metadata, NULL, 10, TRUE, NULL);

    if (argv[fileindex] != NULL) {
#ifdef GIO_ENABLED
        file = g_file_new_for_commandline_arg(argv[fileindex]);
        stat_result = -1;
        if (file != NULL) {
            GError *error = NULL;
            GFileInfo *file_info = g_file_query_info(file, G_FILE_ATTRIBUTE_UNIX_MODE, 0, NULL, &error);
            if (file_info != NULL) {
                buf.st_mode = g_file_info_get_attribute_uint32(file_info, G_FILE_ATTRIBUTE_UNIX_MODE);
                stat_result = 0;
                g_object_unref(file_info);
            }
            if (error != NULL) {
                if (verbose)
                    printf("failed to get mode: %s\n", error->message);
                g_error_free(error);
            }
            g_object_unref(file);
        }
#else
        stat_result = g_stat(argv[fileindex], &buf);
#endif

        if (verbose) {
            printf("opening %s\n", argv[fileindex]);
            printf("stat_result = %i\n", stat_result);
            printf("is block %i\n", S_ISBLK(buf.st_mode));
            printf("is character %i\n", S_ISCHR(buf.st_mode));
            printf("is reg %i\n", S_ISREG(buf.st_mode));
            printf("is dir %i\n", S_ISDIR(buf.st_mode));
            printf("playlist %i\n", playlist);
            printf("embedded in window id 0x%x\n", embed_window);
        }
        if (stat_result == 0 && S_ISBLK(buf.st_mode)) {
            // might have a block device, so could be a DVD

#ifdef HAVE_SYS_MOUNT_H
            fp = setmntent("/etc/mtab", "r");
            do {
                mnt = getmntent(fp);
                if (mnt)
                    printf("%s is at %s\n", mnt->mnt_fsname, mnt->mnt_dir);
                if (argv[fileindex] != NULL && mnt && mnt->mnt_fsname != NULL) {
                    if (strcmp(argv[fileindex], mnt->mnt_fsname) == 0)
                        break;
                }
            }
            while (mnt);
            endmntent(fp);
#endif
            if (mnt && mnt->mnt_dir) {
                printf("%s is mounted on %s\n", argv[fileindex], mnt->mnt_dir);
                uri = g_strdup_printf("%s/VIDEO_TS", mnt->mnt_dir);
                stat(uri, &buf);
                g_free(uri);
                if (S_ISDIR(buf.st_mode)) {
                    add_item_to_playlist("dvdnav://", 0);
                    gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                    gmtk_media_player_set_media_type(GMTK_MEDIA_PLAYER(media), TYPE_DVD);
                    //play_iter(&iter, 0);
                    playiter = TRUE;
                } else {
                    uri = g_strdup_printf("file://%s", mnt->mnt_dir);
                    create_folder_progress_window();
                    add_folder_to_playlist_callback(uri, NULL);
                    g_free(uri);
                    destroy_folder_progress_window();
                    if (random_order) {
                        gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                        randomize_playlist(playliststore);
                    }
                    if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter)) {
                        // play_iter(&iter, 0);
                        playiter = TRUE;
                    }
                }
            } else {
                parse_cdda("cdda://");
                if (random_order) {
                    gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                    randomize_playlist(playliststore);
                }
                //play_file("cdda://", playlist);
                if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter)) {
                    // play_iter(&iter, 0);
                    playiter = TRUE;
                }
            }
        } else if (stat_result == 0 && S_ISDIR(buf.st_mode)) {
            uri = g_strdup_printf("%s/VIDEO_TS", argv[fileindex]);
            stat_result = g_stat(uri, &buf);
            g_free(uri);
            if (stat_result == 0 && S_ISDIR(buf.st_mode)) {
                add_item_to_playlist("dvdnav://", 0);
                gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                gmtk_media_player_set_media_type(GMTK_MEDIA_PLAYER(media), TYPE_DVD);
                //play_iter(&iter, 0);
                playiter = TRUE;
            } else {
                create_folder_progress_window();
                uri = NULL;
#ifdef GIO_ENABLED
                file = g_file_new_for_commandline_arg(argv[fileindex]);
                if (file != NULL) {
                    uri = g_file_get_uri(file);
                    g_object_unref(file);
                }
#else
                uri = g_filename_to_uri(argv[fileindex], NULL, NULL);
#endif
                add_folder_to_playlist_callback(uri, NULL);
                g_free(uri);
                destroy_folder_progress_window();
                if (random_order) {
                    gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                    randomize_playlist(playliststore);
                }
                if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter)) {
                    //play_iter(&iter, 0);
                    playiter = TRUE;
                }
            }
        } else {
            // local file
            // detect if playlist here, so even if not specified it can be picked up
            i = fileindex;

            while (argv[i] != NULL) {
                if (verbose > 1)
                    printf("Argument %i is %s\n", i, argv[i]);
#ifdef GIO_ENABLED
                if (!device_name(argv[i])) {
                    file = g_file_new_for_commandline_arg(argv[i]);
                    if (file != NULL) {
                        uri = g_file_get_uri(file);
                        g_object_unref(file);
                    } else {
                        uri = g_strdup(argv[i]);
                    }
                } else {
                    uri = g_strdup(argv[i]);
                }
#else
                uri = g_filename_to_uri(argv[i], NULL, NULL);
#endif

                if (uri != NULL) {
                    if (playlist == 0)
                        playlist = detect_playlist(uri);
                    if (!playlist) {
                        add_item_to_playlist(uri, playlist);
                    } else {
                        if (!parse_playlist(uri)) {
                            add_item_to_playlist(uri, playlist);
                        }
                    }
                    g_free(uri);
                }
                i++;
            }

            if (random_order) {
                gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                randomize_playlist(playliststore);
            }
            if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter)) {
                // play_iter(&iter, 0);
                playiter = TRUE;
            }
        }

    }
#ifdef HAVE_GPOD
    if (load_tracks_from_gpod) {
        gpod_mount_point = find_gpod_mount_point();
        printf("mount point is %s\n", gpod_mount_point);
        if (gpod_mount_point != NULL) {
            gpod_load_tracks(gpod_mount_point);
        } else {
            printf("Unable to find gpod mount point\n");
        }
    }
#endif

    gm_audio_update_device(&audio_device);
    gm_audio_get_volume(&audio_device);
    gm_audio_set_server_volume_update_callback(&audio_device, set_volume);
    set_media_player_attributes(media);

    if (!softvol) {
        if (pref_volume != -1) {
            audio_device.volume = (gdouble) pref_volume / 100.0;
        }
        if (verbose)
            printf("The volume on '%s' is %f\n", audio_device.description, audio_device.volume);
        volume = audio_device.volume * 100;
    } else {
        audio_device.volume = volume / 100.0;
    }
#ifdef GTK2_12_ENABLED
    gtk_scale_button_set_value(GTK_SCALE_BUTTON(vol_slider), audio_device.volume);
#else
    gtk_range_set_value(GTK_RANGE(vol_slider), audio_device.volume);
#endif
    use_volume_option = detect_volume_option();

    dbus_hookup(embed_window, control_id);
    show_window(embed_window);

    if (playiter)
        play_iter(&iter, 0);

    if (argv[fileindex] == NULL && embed_window == 0) {
        // When running as apple.com external player, don't load the default playlist
        if (control_id == 0) {
            use_remember_loc = remember_loc;
            gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem_view_playlist), playlist_visible);
        } else {
            remember_loc = FALSE;
            use_remember_loc = FALSE;
            // prevents saving of a playlist with one item on it
            use_defaultpl = FALSE;
            // don't save the loc when launched with a single file
            save_loc = FALSE;
        }
    } else {
        // prevents saving of a playlist with one item on it
        use_defaultpl = FALSE;
        // don't save the loc when launched with a single file
        save_loc = FALSE;
    }

    if (single_instance && embed_window == 0) {
        if (control_id == 0) {
            use_remember_loc = remember_loc;
            gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem_view_playlist), playlist_visible);
        }
    }

    if (embed_window == 0) {
        if (remember_loc) {
            gtk_window_move(GTK_WINDOW(window), loc_window_x, loc_window_y);
            g_idle_add(set_pane_position, NULL);

        }
    }

    safe_to_save_default_playlist = FALSE;
    if (use_defaultpl) {
        create_folder_progress_window();
        parse_playlist(default_playlist);
        destroy_folder_progress_window();
    }
    safe_to_save_default_playlist = TRUE;

    gtk_main();

    return 0;
}
int main() {
    cl_int error_code = CL_SUCCESS;

    try {
        // find Intel platform
        cl_uint num_platforms = 0;
        error_code = clGetPlatformIDs(0, nullptr, &num_platforms);
        HANDLE_CL_ERROR(clGetPlatformIDs)
        std::unique_ptr<cl_platform_id[]> platform_ids(
                new cl_platform_id[static_cast<const std::size_t>(num_platforms)]);
        error_code = clGetPlatformIDs(num_platforms, platform_ids.get(), nullptr);
        HANDLE_CL_ERROR(clGetPlatformIDs)
        cl_platform_id platform = nullptr;
        for (std::size_t i = 0; i != static_cast<const std::size_t>(num_platforms); ++i) {
            std::size_t platform_name_size = 0;
            error_code = clGetPlatformInfo(platform_ids[i], CL_PLATFORM_NAME, 0, nullptr, &platform_name_size);
            HANDLE_CL_ERROR(clGetPlatformInfo)
            std::unique_ptr<char[]> platform_name(new char[platform_name_size]);
            error_code = clGetPlatformInfo(platform_ids[i], CL_PLATFORM_NAME,
                                           platform_name_size, platform_name.get(), nullptr);
            HANDLE_CL_ERROR(clGetPlatformInfo)
            if (std::strcmp(beignet_platform_name, platform_name.get()) == 0) {
                platform = platform_ids[i];
                std::cout << "Platform: " << platform_name.get() << std::endl;
                break;
            }
        }
        if (platform == nullptr) {
            throw std::runtime_error(std::string("Couldn't find platform with name: ") + beignet_platform_name);
        }

        // find Intel GPU
        cl_device_id device = nullptr;
        error_code = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, nullptr);
        HANDLE_CL_ERROR(clGetDeviceIDs)
        std::size_t device_name_size = 0;
        error_code = clGetDeviceInfo(device, CL_DEVICE_NAME, 0, nullptr, &device_name_size);
        HANDLE_CL_ERROR(clGetDeviceInfo)
        std::unique_ptr<char[]> device_name(new char[device_name_size]);
        error_code = clGetDeviceInfo(device, CL_DEVICE_NAME, device_name_size, device_name.get(), nullptr);
        HANDLE_CL_ERROR(clGetDeviceInfo)
        std::cout << "Device: " << device_name.get() << std::endl;

        // create OpenCL context, command queue, program and kernel
        const auto context = clCreateContext(nullptr, 1, &device, nullptr, nullptr, &error_code);
        HANDLE_CL_ERROR(clCreateContext)
        const auto command_queue = clCreateCommandQueue(context, device, 0, &error_code);
        HANDLE_CL_ERROR(clCreateCommandQueue)

        const char *source_strings[1];
        source_strings[0] = kernel_source;
        const std::size_t source_size = std::strlen(kernel_source);
        const auto program = clCreateProgramWithSource(context, 1, source_strings, &source_size, &error_code);
        HANDLE_CL_ERROR(clCreateProgramWithSource)
        error_code = clBuildProgram(program, 1, &device, "", nullptr, nullptr);
        HANDLE_CL_ERROR(clBuildProgram)
        const auto kernel = clCreateKernel(program, "print_hello", &error_code);
        HANDLE_CL_ERROR(clCreateKernel)

        // enqueue kernel and set event completion handler
        cl_event event;
        std::size_t global_work_size = 1;
        error_code = clEnqueueNDRangeKernel(command_queue, kernel, 1, nullptr, &global_work_size, nullptr,
                                            0, nullptr, &event);
        HANDLE_CL_ERROR(clEnqueueNDRangeKernel)

        error_code = clSetEventCallback(event, CL_COMPLETE, [](cl_event, cl_int, void *) {
            std::cout << "OpenCL callback" << std::endl;
            // Notify the waiting thread that the kernel is completed
            {
                std::lock_guard<std::mutex> cond_lock(cond_mutex);
                kernel_complete = true;
            }
            cond_var.notify_one();
        }, nullptr);
        HANDLE_CL_ERROR(clSetEventCallback)

        error_code = clFlush(command_queue);
        HANDLE_CL_ERROR(clFlush)

        // simulate work
        std::this_thread::sleep_for(std::chrono::seconds(1));

        // do work, dependent on kernel completion
        {
            std::unique_lock<std::mutex> cond_lock(cond_mutex);
            while (!kernel_complete) {
                if (cond_var.wait_for(cond_lock, std::chrono::seconds(5)) == std::cv_status::timeout) {
                    std::cout << "WARNING: A 5 second timeout has been reached on the condition variable.\n"
                            "         This may be a deadlock." << std::endl;
                }
            }
        }
        // When using Beignet, this will never be called as a deadlock will occur.
        std::cout << "Doing work, dependent on the kernel's completion" << std::endl;
    } catch (const std::exception &e) {
        std::cout << "Error: " << e.what() << std::endl;
    } catch (...) {
        std::cout << "Unknown error" << std::endl;
    }
}
Пример #20
0
/**
 * @todo Figure out the way to minimize code duplication
 */
bool
ActionLog::LookupActionsForFile(
  const function<void(const Name& name, sqlite3_int64 seq_no, const ActionItem&)>& visitor,
  const std::string& file, int offset /*=0*/, int limit /*=-1*/)
{
  _LOG_DEBUG("LookupActionsInFolderRecursively: [" << file << "]");
  if (file.empty())
    return false;

  if (limit >= 0)
    limit += 1; // to check if there is more data

  sqlite3_stmt* stmt;
  sqlite3_prepare_v2(m_db,
                     "SELECT device_name,seq_no,action,filename,directory,version,strftime('%s', action_timestamp), "
                     "       file_hash,strftime('%s', file_mtime),file_chmod,file_seg_num, "
                     "       parent_device_name,parent_seq_no "
                     "   FROM ActionLog "
                     "   WHERE filename=? "
                     "   ORDER BY action_timestamp DESC "
                     "   LIMIT ? OFFSET ?",
                     -1, &stmt,
                     0); // there is a small ambiguity with is_prefix matching, but should be ok for now
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_text(stmt, 1, file.c_str(), file.size(), SQLITE_STATIC);
  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  sqlite3_bind_int(stmt, 2, limit);
  sqlite3_bind_int(stmt, 3, offset);

  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_OK, sqlite3_errmsg(m_db));

  while (sqlite3_step(stmt) == SQLITE_ROW) {
    if (limit == 1)
      break;

    ActionItem action;

    Name device_name(Block(reinterpret_cast<const uint8_t*>(sqlite3_column_blob(stmt, 0)),
                           sqlite3_column_bytes(stmt, 0)));

    sqlite3_int64 seq_no = sqlite3_column_int64(stmt, 1);
    action.set_action(static_cast<ActionItem_ActionType>(sqlite3_column_int(stmt, 2)));
    action.set_filename(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3)),
                        sqlite3_column_bytes(stmt, 3));
    std::string directory(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 4)),
                          sqlite3_column_bytes(stmt, 4));
    action.set_version(sqlite3_column_int64(stmt, 5));
    action.set_timestamp(sqlite3_column_int64(stmt, 6));

    if (action.action() == 0) {
      action.set_file_hash(sqlite3_column_blob(stmt, 7), sqlite3_column_bytes(stmt, 7));
      action.set_mtime(sqlite3_column_int(stmt, 8));
      action.set_mode(sqlite3_column_int(stmt, 9));
      action.set_seg_num(sqlite3_column_int64(stmt, 10));
    }
    if (sqlite3_column_bytes(stmt, 11) > 0) {
      action.set_parent_device_name(sqlite3_column_blob(stmt, 11), sqlite3_column_bytes(stmt, 11));
      action.set_parent_seq_no(sqlite3_column_int64(stmt, 12));
    }

    visitor(device_name, seq_no, action);
    limit--;
  }

  _LOG_DEBUG_COND(sqlite3_errcode(m_db) != SQLITE_DONE, sqlite3_errmsg(m_db));

  sqlite3_finalize(stmt);

  return (limit == 1); // more data is available
}
Пример #21
0
static void
update_for_binary_section(bfd *abfd,
			  asection *the_section,
			  PTR obj)
{
  unsigned_word section_vma;
  unsigned_word section_size;
  access_type access;
  device *me = (device*)obj;

  /* skip the section if no memory to allocate */
  if (! (bfd_get_section_flags(abfd, the_section) & SEC_ALLOC))
    return;

  /* check/ignore any sections of size zero */
  section_size = bfd_get_section_size_before_reloc(the_section);
  if (section_size == 0)
    return;

  /* find where it is to go */
  section_vma = bfd_get_section_vma(abfd, the_section);

  DTRACE(binary,
	 ("name=%-7s, vma=0x%.8lx, size=%6ld, flags=%3lx(%s%s%s%s%s )\n",
	  bfd_get_section_name(abfd, the_section),
	  (long)section_vma,
	  (long)section_size,
	  (long)bfd_get_section_flags(abfd, the_section),
	  bfd_get_section_flags(abfd, the_section) & SEC_LOAD ? " LOAD" : "",
	  bfd_get_section_flags(abfd, the_section) & SEC_CODE ? " CODE" : "",
	  bfd_get_section_flags(abfd, the_section) & SEC_DATA ? " DATA" : "",
	  bfd_get_section_flags(abfd, the_section) & SEC_ALLOC ? " ALLOC" : "",
	  bfd_get_section_flags(abfd, the_section) & SEC_READONLY ? " READONLY" : ""
	  ));

  /* If there is an .interp section, it means it needs a shared library interpreter.  */
  if (strcmp(".interp", bfd_get_section_name(abfd, the_section)) == 0)
    error("Shared libraries are not yet supported.\n");

  /* determine the devices access */
  access = access_read;
  if (bfd_get_section_flags(abfd, the_section) & SEC_CODE)
    access |= access_exec;
  if (!(bfd_get_section_flags(abfd, the_section) & SEC_READONLY))
    access |= access_write;

  /* if claim specified, allocate region from the memory device */
  if (device_find_property(me, "claim") != NULL) {
    device_instance *memory = tree_find_ihandle_property(me, "/chosen/memory");
    unsigned_cell mem_in[3];
    unsigned_cell mem_out[1];
    mem_in[0] = 0; /*alignment - top-of-stack*/
    mem_in[1] = section_size;
    mem_in[2] = section_vma;
    if (device_instance_call_method(memory, "claim", 3, mem_in, 1, mem_out) < 0)
      device_error(me, "failed to claim memory for section at 0x%lx (0x%lx",
		   section_vma,
		   section_size);
    if (mem_out[0] != section_vma)
      device_error(me, "section address not as requested");
  }

  /* if a map, pass up a request to create the memory in core */
  if (strncmp(device_name(me), "map-binary", strlen("map-binary")) == 0)
    device_attach_address(device_parent(me),
			  attach_raw_memory,
			  0 /*address space*/,
			  section_vma,
			  section_size,
			  access,
			  me);

  /* if a load dma in the required data */
  if (bfd_get_section_flags(abfd, the_section) & SEC_LOAD) {
    void *section_init = zalloc(section_size);
    if (!bfd_get_section_contents(abfd,
				  the_section,
				  section_init, 0,
				  section_size)) {
      bfd_perror("binary");
      device_error(me, "load of data failed");
      return;
    }
    if (device_dma_write_buffer(device_parent(me),
				section_init,
				0 /*space*/,
				section_vma,
				section_size,
				1 /*violate_read_only*/)
	!= section_size)
      device_error(me, "broken transfer\n");
    zfree(section_init); /* only free if load */
  }
}
Пример #22
0
split_find_device(device *current,
		  name_specifier *spec)
{
  /* strip off (and process) any leading ., .., ./ and / */
  while (1) {
    if (strncmp(spec->path, "/", strlen("/")) == 0) {
      /* cd /... */
      while (current != NULL && device_parent(current) != NULL)
	current = device_parent(current);
      spec->path += strlen("/");
    }
    else if (strncmp(spec->path, "./", strlen("./")) == 0) {
      /* cd ./... */
      current = current;
      spec->path += strlen("./");
    }
    else if (strncmp(spec->path, "../", strlen("../")) == 0) {
      /* cd ../... */
      if (current != NULL && device_parent(current) != NULL)
	current = device_parent(current);
      spec->path += strlen("../");
    }
    else if (strcmp(spec->path, ".") == 0) {
      /* cd . */
      current = current;
      spec->path += strlen(".");
    }
    else if (strcmp(spec->path, "..") == 0) {
      /* cd . */
      if (current != NULL && device_parent(current) != NULL)
	current = device_parent(current);
      spec->path += strlen("..");
    }
    else
      break;
  }

  /* now go through the path proper */

  if (current == NULL) {
    split_device_name(spec);
    return NULL;
  }

  while (split_device_name(spec)) {
    device *child;
    for (child = device_child(current);
	 child != NULL; child = device_sibling(child)) {
      if (strcmp(spec->name, device_name(child)) == 0) {
	if (spec->unit == NULL)
	  break;
	else {
	  device_unit phys;
	  device_decode_unit(current, spec->unit, &phys);
	  if (memcmp(&phys, device_unit_address(child),
		     sizeof(device_unit)) == 0)
	    break;
	}
      }
    }
    if (child == NULL)
      return current; /* search failed */
    current = child;
  }

  return current;
}
Пример #23
0
Файл: s98d.c Проект: autch/s98ml
int main(int ac, char** av)
{
    struct s98context context;
    struct s98context* ctx = &context;
    struct s98header* h = &context.header;
    FILE* fp;

    if(ac != 2) {
        fprintf(stderr, "Usage: %s filename.s98\n", *av);
        return 1;
    }

    fp = fopen(*++av, "rb");
    if(fp == NULL) {
        perror(*av);
        return -1;
    }

    memset(ctx, 0, sizeof context);

    fseek(fp, 0, SEEK_END);
    ctx->s98_size = ftell(fp);
    ctx->s98_buffer = malloc(ctx->s98_size);

    rewind(fp);
    fread(ctx->s98_buffer, 1, ctx->s98_size, fp);
    set_offset(ctx, 0);
    fclose(fp);

    if(read_header(ctx) != 0)
        goto cleanup;
    read_devices(ctx);

    printf("; S98 File: %s\n", *av);
    printf("; Offset to tag: 0x%08x (0 if none)\n", h->offset_to_tag);
    printf("; Dump start: 0x%08x\n", h->offset_to_dump);
    printf("; Loop start: 0x%08x (0 if non-looped)\n", h->offset_to_loop);

    printf("#version %d\n", h->version);
    printf("#timer %d/%d\n", h->timer_numerator, h->timer_denominator);

    read_tag(ctx);

    putchar('\n');
    {
        int i;
        for(i = 0; i < h->device_count; i++) {
            struct s98deviceinfo* info;
            info = ctx->devices + i;

            printf("#device %s %d $%02x\n", device_name(info->device), info->clock, info->panpot);
        }
    }

    putchar('\n');

    s98d_dump(ctx);

    putchar('\n');


cleanup:
    free_context(&context);

    return 0;
}
Пример #24
0
static int add_mount(const char *what, const char *where, struct mntent *me) {
        char *name = NULL, *unit = NULL, *lnk = NULL, *device = NULL, *automount_name = NULL, *automount_unit = NULL;
        FILE *f = NULL;
        bool noauto, nofail, automount, isbind, isnetwork;
        int r;
        const char *post, *pre;

        assert(what);
        assert(where);
        assert(me);

        if (streq(me->mnt_type, "autofs"))
                return 0;

        if (!is_path(where)) {
                log_warning("Mount point %s is not a valid path, ignoring.", where);
                return 0;
        }

        if (mount_point_is_api(where) ||
            mount_point_ignore(where))
                return 0;

        isnetwork = mount_is_network(me);
        isbind = mount_is_bind(me);

        noauto = !!hasmntopt(me, "noauto");
        nofail = !!hasmntopt(me, "nofail");
        automount =
                hasmntopt(me, "comment=systemd.automount") ||
                hasmntopt(me, "x-systemd.automount");

        if (isnetwork) {
                post = SPECIAL_REMOTE_FS_TARGET;
                pre = SPECIAL_REMOTE_FS_PRE_TARGET;
        } else {
                post = SPECIAL_LOCAL_FS_TARGET;
                pre = SPECIAL_LOCAL_FS_PRE_TARGET;
        }

        name = unit_name_from_path(where, ".mount");
        if (!name) {
                r = log_oom();
                goto finish;
        }

        unit = strjoin(arg_dest, "/", name, NULL);
        if (!unit) {
                r = log_oom();
                goto finish;
        }

        f = fopen(unit, "wxe");
        if (!f) {
                r = -errno;
                log_error("Failed to create unit file: %m");
                goto finish;
        }

        fputs("# Automatically generated by systemd-fstab-generator\n\n"
              "[Unit]\n"
              "SourcePath=/etc/fstab\n"
              "DefaultDependencies=no\n", f);

        if (!path_equal(where, "/"))
                fprintf(f,
                        "After=%s\n"
                        "Wants=%s\n"
                        "Conflicts=" SPECIAL_UMOUNT_TARGET "\n"
                        "Before=" SPECIAL_UMOUNT_TARGET "\n",
                        pre,
                        pre);


        if (!noauto && !nofail && !automount)
                fprintf(f,
                        "Before=%s\n",
                        post);

        fprintf(f,
                "\n"
                "[Mount]\n"
                "What=%s\n"
                "Where=%s\n"
                "Type=%s\n"
                "FsckPassNo=%i\n",
                what,
                where,
                me->mnt_type,
                me->mnt_passno);

        if (!isempty(me->mnt_opts) &&
            !streq(me->mnt_opts, "defaults"))
                fprintf(f,
                        "Options=%s\n",
                        me->mnt_opts);

        fflush(f);
        if (ferror(f)) {
                log_error("Failed to write unit file: %m");
                r = -errno;
                goto finish;
        }

        if (!noauto) {
                lnk = strjoin(arg_dest, "/", post, nofail || automount ? ".wants/" : ".requires/", name, NULL);
                if (!lnk) {
                        r = log_oom();
                        goto finish;
                }

                mkdir_parents_label(lnk, 0755);
                if (symlink(unit, lnk) < 0) {
                        log_error("Failed to create symlink: %m");
                        r = -errno;
                        goto finish;
                }

                if (!isbind &&
                    !path_equal(where, "/")) {

                        r = device_name(what, &device);
                        if (r < 0)
                                goto finish;

                        if (r > 0) {
                                free(lnk);
                                lnk = strjoin(arg_dest, "/", device, ".wants/", name, NULL);
                                if (!lnk) {
                                        r = log_oom();
                                        goto finish;
                                }

                                mkdir_parents_label(lnk, 0755);
                                if (symlink(unit, lnk) < 0) {
                                        log_error("Failed to create symlink: %m");
                                        r = -errno;
                                        goto finish;
                                }
                        }
                }
        }

        if (automount && !path_equal(where, "/")) {
                automount_name = unit_name_from_path(where, ".automount");
                if (!name) {
                        r = log_oom();
                        goto finish;
                }

                automount_unit = strjoin(arg_dest, "/", automount_name, NULL);
                if (!automount_unit) {
                        r = log_oom();
                        goto finish;
                }

                fclose(f);
                f = fopen(automount_unit, "wxe");
                if (!f) {
                        r = -errno;
                        log_error("Failed to create unit file: %m");
                        goto finish;
                }

                fprintf(f,
                        "# Automatically generated by systemd-fstab-generator\n\n"
                        "[Unit]\n"
                        "SourcePath=/etc/fstab\n"
                        "DefaultDependencies=no\n"
                        "Conflicts=" SPECIAL_UMOUNT_TARGET "\n"
                        "Before=" SPECIAL_UMOUNT_TARGET " %s\n"
                        "\n"
                        "[Automount]\n"
                        "Where=%s\n",
                        post,
                        where);

                fflush(f);
                if (ferror(f)) {
                        log_error("Failed to write unit file: %m");
                        r = -errno;
                        goto finish;
                }

                free(lnk);
                lnk = strjoin(arg_dest, "/", post, nofail ? ".wants/" : ".requires/", automount_name, NULL);
                if (!lnk) {
                        r = log_oom();
                        goto finish;
                }

                mkdir_parents_label(lnk, 0755);
                if (symlink(automount_unit, lnk) < 0) {
                        log_error("Failed to create symlink: %m");
                        r = -errno;
                        goto finish;
                }
        }

        r = 0;
finish:
        if (f)
                fclose(f);

        free(unit);
        free(lnk);
        free(name);
        free(device);
        free(automount_name);
        free(automount_unit);

        return r;
}
Пример #25
0
VirtioBlk::VirtioBlk(hw::PCI_Device& d)
  : Virtio(d), hw::Block_device(), req(device_name() + ".req0", queue_size(0), 0, iobase()), inflight(0)
{
  INFO("VirtioBlk", "Initializing");
  {
    auto& reqs = Statman::get().create(
      Stat::UINT32, device_name() + ".requests");
    this->requests = &reqs.get_uint32();
    *this->requests = 0;

    auto& err = Statman::get().create(
      Stat::UINT32, device_name() + ".errors");
    this->errors = &err.get_uint32();
    *this->errors = 0;
  }

  uint32_t needed_features =
    FEAT(VIRTIO_BLK_F_BLK_SIZE);
  negotiate_features(needed_features);

  CHECK(features() & FEAT(VIRTIO_BLK_F_BARRIER),
        "Barrier is enabled");
  CHECK(features() & FEAT(VIRTIO_BLK_F_SIZE_MAX),
        "Size-max is known");
  CHECK(features() & FEAT(VIRTIO_BLK_F_SEG_MAX),
        "Seg-max is known");
  CHECK(features() & FEAT(VIRTIO_BLK_F_GEOMETRY),
        "Geometry structure is used");
  CHECK(features() & FEAT(VIRTIO_BLK_F_RO),
        "Device is read-only");
  CHECK(features() & FEAT(VIRTIO_BLK_F_BLK_SIZE),
        "Block-size is known");
  CHECK(features() & FEAT(VIRTIO_BLK_F_SCSI),
        "SCSI is enabled :(");
  CHECK(features() & FEAT(VIRTIO_BLK_F_FLUSH),
        "Flush enabled");

  CHECK ((features() & needed_features) == needed_features,
         "Negotiated needed features");

  // Step 1 - Initialize REQ queue
  auto success = assign_queue(0, req.queue_desc());
  CHECK(success, "Request queue assigned (%p) to device",
        req.queue_desc());

  // Step 3 - Fill receive queue with buffers
  // DEBUG: Disable
  INFO("VirtioBlk", "Queue size: %i\tRequest size: %zu\n",
       req.size(), sizeof(request_t));

  // Get device configuration
  get_config();

  // Signal setup complete.
  setup_complete((features() & needed_features) == needed_features);
  CHECK((features() & needed_features) == needed_features, "Signalled driver OK");

  // Hook up IRQ handler (inherited from Virtio)
  if (has_msix())
  {
    assert(get_msix_vectors() >= 2);
    auto& irqs = this->get_irqs();
    // update IRQ subscriptions
    Events::get().subscribe(irqs[0], {this, &VirtioBlk::service_RX});
    Events::get().subscribe(irqs[1], {this, &VirtioBlk::msix_conf_handler});
  }
  else
  {
    auto& irqs = this->get_irqs();
    Events::get().subscribe(irqs[0], {this, &VirtioBlk::irq_handler});
  }

  // Done
  INFO("VirtioBlk", "Block device with %zu sectors capacity", config.capacity);
}
Пример #26
0
static int add_swap(const char *what, struct mntent *me) {
        char *name = NULL, *unit = NULL, *lnk = NULL, *device = NULL;
        FILE *f = NULL;
        bool noauto, nofail;
        int r, pri = -1;

        assert(what);
        assert(me);

        r = mount_find_pri(me, &pri);
        if (r < 0) {
                log_error("Failed to parse priority");
                return pri;
        }

        noauto = !!hasmntopt(me, "noauto");
        nofail = !!hasmntopt(me, "nofail");

        name = unit_name_from_path(what, ".swap");
        if (!name) {
                r = log_oom();
                goto finish;
        }

        unit = strjoin(arg_dest, "/", name, NULL);
        if (!unit) {
                r = log_oom();
                goto finish;
        }

        f = fopen(unit, "wxe");
        if (!f) {
                r = -errno;
                log_error("Failed to create unit file: %m");
                goto finish;
        }

        fputs("# Automatically generated by systemd-fstab-generator\n\n"
              "[Unit]\n"
              "SourcePath=/etc/fstab\n"
              "DefaultDependencies=no\n"
              "Conflicts=" SPECIAL_UMOUNT_TARGET "\n"
              "Before=" SPECIAL_UMOUNT_TARGET "\n", f);

        if (!noauto && !nofail)
                fputs("Before=" SPECIAL_SWAP_TARGET "\n", f);

        fprintf(f,
                "\n"
                "[Swap]\n"
                "What=%s\n",
                what);

        if (pri >= 0)
                fprintf(f,
                        "Priority=%i\n",
                        pri);

        fflush(f);
        if (ferror(f)) {
                log_error("Failed to write unit file: %m");
                r = -errno;
                goto finish;
        }

        if (!noauto) {
                lnk = strjoin(arg_dest, "/" SPECIAL_SWAP_TARGET ".wants/", name, NULL);
                if (!lnk) {
                        r = log_oom();
                        goto finish;
                }

                mkdir_parents_label(lnk, 0755);
                if (symlink(unit, lnk) < 0) {
                        log_error("Failed to create symlink: %m");
                        r = -errno;
                        goto finish;
                }

                r = device_name(what, &device);
                if (r < 0)
                        goto finish;

                if (r > 0) {
                        free(lnk);
                        lnk = strjoin(arg_dest, "/", device, ".wants/", name, NULL);
                        if (!lnk) {
                                r = log_oom();
                                goto finish;
                        }

                        mkdir_parents_label(lnk, 0755);
                        if (symlink(unit, lnk) < 0) {
                                log_error("Failed to create symlink: %m");
                                r = -errno;
                                goto finish;
                        }
                }
        }

        r = 0;
finish:
        if (f)
                fclose(f);

        free(unit);
        free(lnk);
        free(name);
        free(device);

        return r;
}
Пример #27
0
/*
 ***************************************************************************
 * Main entry to the iostat program.
 ***************************************************************************
 */
int main(int argc, char **argv)
{
	int it = 0;
	int opt = 1;
	int i, report_set = FALSE;
	long count = 1;
	struct utsname header;
	struct io_dlist *st_dev_list_i;
	struct tm rectime;
	char *t, *persist_devname, *devname;

#ifdef USE_NLS
	/* Init National Language Support */
	init_nls();
#endif

	/* Get HZ */
	get_HZ();

	/* Allocate structures for device list */
	if (argc > 1) {
		salloc_dev_list(argc - 1 + count_csvalues(argc, argv));
	}

	/* Process args... */
	while (opt < argc) {

		/* -p option used individually. See below for grouped use */
		if (!strcmp(argv[opt], "-p")) {
			flags |= I_D_PARTITIONS;
			if (argv[++opt] &&
			    (strspn(argv[opt], DIGITS) != strlen(argv[opt])) &&
			    (strncmp(argv[opt], "-", 1))) {
				flags |= I_D_UNFILTERED;

				for (t = strtok(argv[opt], ","); t; t = strtok(NULL, ",")) {
					if (!strcmp(t, K_ALL)) {
						flags |= I_D_PART_ALL;
					}
					else {
						devname = device_name(t);
						if (DISPLAY_PERSIST_NAME_I(flags)) {
							/* Get device persistent name */
							persist_devname = get_pretty_name_from_persistent(devname);
							if (persist_devname != NULL) {
								devname = persist_devname;
							}
						}
						/* Store device name */
						i = update_dev_list(&dlist_idx, devname);
						st_dev_list_i = st_dev_list + i;
						st_dev_list_i->disp_part = TRUE;
					}
				}
				opt++;
			}
			else {
				flags |= I_D_PART_ALL;
			}
		}

		else if (!strcmp(argv[opt], "-g")) {
			/*
			 * Option -g: Stats for a group of devices.
			 * group_name contains the last group name entered on
			 * the command line. If we define an additional one, save
			 * the previous one in the list. We do that this way because we
			 * want the group name to appear in the list _after_ all
			 * the devices included in that group. The last group name
			 * will be saved in the list later, in presave_device_list() function.
			 */
			if (group_nr > 0) {
				update_dev_list(&dlist_idx, group_name);
			}
			if (argv[++opt]) {
				/*
				 * MAX_NAME_LEN - 2: one char for the heading space,
				 * and one for the trailing '\0'.
				 */
				snprintf(group_name, MAX_NAME_LEN, " %-.*s", MAX_NAME_LEN - 2, argv[opt++]);
			}
			else {
				usage(argv[0]);
			}
			group_nr++;
		}

		else if (!strcmp(argv[opt], "-j")) {
			if (argv[++opt]) {
				if (strnlen(argv[opt], MAX_FILE_LEN) >= MAX_FILE_LEN - 1) {
					usage(argv[0]);
				}
				strncpy(persistent_name_type, argv[opt], MAX_FILE_LEN - 1);
				persistent_name_type[MAX_FILE_LEN - 1] = '\0';
				strtolower(persistent_name_type);
				/* Check that this is a valid type of persistent device name */
				if (!get_persistent_type_dir(persistent_name_type)) {
					fprintf(stderr, _("Invalid type of persistent device name\n"));
					exit(1);
				}
				/*
				 * Persistent names are usually long: Display
				 * them as human readable by default.
				 */
				flags |= I_D_PERSIST_NAME + I_D_HUMAN_READ;
				opt++;
			}
			else {
				usage(argv[0]);
			}
		}

#ifdef DEBUG
		else if (!strcmp(argv[opt], "--debuginfo")) {
			flags |= I_D_DEBUG;
			opt++;
		}
#endif

		else if (!strncmp(argv[opt], "-", 1)) {
			for (i = 1; *(argv[opt] + i); i++) {

				switch (*(argv[opt] + i)) {

				case 'c':
					/* Display cpu usage */
					flags |= I_D_CPU;
					report_set = TRUE;
					break;

				case 'd':
					/* Display disk utilization */
					flags |= I_D_DISK;
					report_set = TRUE;
					break;

				case 'h':
					/*
					 * Display device utilization report
					 * in a human readable format.
					 */
					flags |= I_D_HUMAN_READ;
					break;

				case 'k':
					if (DISPLAY_MEGABYTES(flags)) {
						usage(argv[0]);
					}
					/* Display stats in kB/s */
					flags |= I_D_KILOBYTES;
					break;

				case 'm':
					if (DISPLAY_KILOBYTES(flags)) {
						usage(argv[0]);
					}
					/* Display stats in MB/s */
					flags |= I_D_MEGABYTES;
					break;

				case 'N':
					/* Display device mapper logical name */
					flags |= I_D_DEVMAP_NAME;
					break;

				case 'p':
					/* If option -p is grouped then it cannot take an arg */
					flags |= I_D_PARTITIONS + I_D_PART_ALL;
					break;

				case 'T':
					/* Display stats only for the groups */
					flags |= I_D_GROUP_TOTAL_ONLY;
					break;

				case 't':
					/* Display timestamp */
					flags |= I_D_TIMESTAMP;
					break;

				case 'x':
					/* Display extended stats */
					flags |= I_D_EXTENDED;
					break;

				case 'y':
					/* Don't display stats since system restart */
					flags |= I_D_OMIT_SINCE_BOOT;
					break;

				case 'z':
					/* Omit output for devices with no activity */
					flags |= I_D_ZERO_OMIT;
					break;

				case 'V':
					/* Print version number and exit */
					print_version();
					break;

				default:
					usage(argv[0]);
				}
			}
			opt++;
		}

		else if (!isdigit(argv[opt][0])) {
			/*
			 * By default iostat doesn't display unused devices.
			 * If some devices are explictly entered on the command line
			 * then don't apply this rule any more.
			 */
			flags |= I_D_UNFILTERED;

			if (strcmp(argv[opt], K_ALL)) {
				/* Store device name entered on the command line */
				devname = device_name(argv[opt++]);
				if (DISPLAY_PERSIST_NAME_I(flags)) {
					persist_devname = get_pretty_name_from_persistent(devname);
					if (persist_devname != NULL) {
						devname = persist_devname;
					}
				}
				update_dev_list(&dlist_idx, devname);
			}
			else {
				opt++;
			}
		}

		else if (!it) {
			interval = atol(argv[opt++]);
			if (interval < 0) {
				usage(argv[0]);
			}
			count = -1;
			it = 1;
		}

		else if (it > 0) {
			count = atol(argv[opt++]);
			if ((count < 1) || !interval) {
				usage(argv[0]);
			}
			it = -1;
		}
		else {
			usage(argv[0]);
		}
	}

	if (!interval) {
		count = 1;
	}

	/* Default: Display CPU and DISK reports */
	if (!report_set) {
		flags |= I_D_CPU + I_D_DISK;
	}
	/*
	 * Also display DISK reports if options -p, -x or a device has been entered
	 * on the command line.
	 */
	if (DISPLAY_PARTITIONS(flags) || DISPLAY_EXTENDED(flags) ||
	    DISPLAY_UNFILTERED(flags)) {
		flags |= I_D_DISK;
	}

	/* Option -T can only be used with option -g */
	if (DISPLAY_GROUP_TOTAL_ONLY(flags) && !group_nr) {
		usage(argv[0]);
	}

	/* Select disk output unit (kB/s or blocks/s) */
	set_disk_output_unit();

	/* Ignore device list if '-p ALL' entered on the command line */
	if (DISPLAY_PART_ALL(flags)) {
		dlist_idx = 0;
	}

	if (DISPLAY_DEVMAP_NAME(flags)) {
		dm_major = get_devmap_major();
	}

	/* Init structures according to machine architecture */
	io_sys_init();
	if (group_nr > 0) {
		/*
		 * If groups of devices have been defined
		 * then save devices and groups in the list.
		 */
		presave_device_list();
	}

	get_localtime(&rectime, 0);

	/* Get system name, release number and hostname */
	uname(&header);
	if (print_gal_header(&rectime, header.sysname, header.release,
			     header.nodename, header.machine, cpu_nr)) {
		flags |= I_D_ISO;
	}
	printf("\n");

	/* Set a handler for SIGALRM */
	memset(&alrm_act, 0, sizeof(alrm_act));
	alrm_act.sa_handler = alarm_handler;
	sigaction(SIGALRM, &alrm_act, NULL);
	alarm(interval);

	/* Main loop */
	rw_io_stat_loop(count, &rectime);

	/* Free structures */
	io_sys_free();
	sfree_dev_list();

	return 0;
}
Пример #28
0
  void open(int device_num)
  {
    // check device_num_range
    if (device_num<0)
      throw std::range_error("negative v4l device number");

    // generate v4l device name
    std::ostringstream device_name_stream;
    device_name_stream << "/dev/video" << device_num;
    std::string device_name(device_name_stream.str());
    
    // check device file
    struct stat stat_buf;
    int error_code = stat(device_name.c_str(), &stat_buf);
    
    if (error_code==-1)
      throw std::runtime_error("could not stat v4l device file: "+std::string(strerror(errno)));

    // is it a character device?
    if (!S_ISCHR(stat_buf.st_mode))
      throw std::runtime_error("devicefile is no character device");

    try
      {
	
    vd = std::auto_ptr<v4l1_device>(new v4l1_device(device_name));

    // get capture dimensions
    video_window videoWindow;
    vd->vidiocgwin(videoWindow);
    m_width=videoWindow.width;
    m_height=videoWindow.height;

    // init memory mapping
    // get mmap info
    video_mbuf videoMBuf;
  
    vd->vidiocgmbuf(videoMBuf);
  
    // check if backbuffering is possible(2 frames)
    if (videoMBuf.frames<2)
      {
	std::string errorMsg;
	errorMsg="mmap cant grab 2 frames";
	throw std::runtime_error(errorMsg);
      }
  
    // start mmapping the framegrabber memory
    m_mmapSize=videoMBuf.size;
  
    m_mmapBase=vd->mmap(m_mmapSize);
  
    // initialize array with startpointer to the mapped frames
    for(int i=0; i!=2; ++i)
    {
      m_frame_ptr.push_back(reinterpret_cast<uint32_t*>(reinterpret_cast<char*>(m_mmapBase)+videoMBuf.offsets[i]));
    }
  
    m_front_buf_idx=0;
    m_back_buf_idx=1;
  
    video_mmap videoMMap; // v4l struct for mmap informations
    videoMMap.frame = m_front_buf_idx; // buffer position
    videoMMap.width = m_width;
    videoMMap.height = m_height;
    
    // probe pixelformats
  // todo - use a set of pixel format and probe each
  try
    {
      // try RGBA
      videoMMap.format =  VIDEO_PALETTE_RGB32;
      vd->vidiocmcapture(videoMMap);
    }
  catch(std::runtime_error& e)
    {
      try
	{
	  // try YUV
	  videoMMap.format =  VIDEO_PALETTE_YUV420P;
	  vd->vidiocmcapture(videoMMap);
	}
      catch(std::runtime_error& e)
	{
	  throw std::runtime_error("error while starting capture to buffer");
	}
    }
  
  m_pixel_format=videoMMap.format;

  m_tmp_img = new uint32_t[m_width*m_height];

      }
    catch(std::runtime_error& e)
      {
	vd.release();
	throw e;
      }
  }