Вверх ↑
Этот топик читают: Гость
Ответов: 2057
Рейтинг: 28
#1: 2021-11-15 23:04:52 ЛС | профиль | цитата
Я хочу сделать компоненты для HiAsm для работы с FFMPEG. Коды хочу взять с сайта https://github.com/Laex/Delphi-FFMPEG.
При попытки скомпилировать код в lazarus он ругается что
decode_video.dpr(29,3) Fatal: Невозможно найти Winapi.Windows, используемый в decode_video в инспекторе проекта.
Где его взять Winapi.Windows?

WinApi.png

Редактировалось 1 раз(а), последний 2021-11-15 23:20:46
карма: 1

0
vip
#1.1контекстная реклама от партнеров
Ответов: 1341
Рейтинг: 31
#2: 2021-11-16 00:08:50 ЛС | профиль | цитата
возможно в среде Delphi 10.3 Rio, FPC 3.0.4, как указано на гитхабе
карма: 2

0
Ответов: 2057
Рейтинг: 28
#3: 2021-11-16 00:19:19 ЛС | профиль | цитата
Rysik писал(а):
возможно в среде Delphi 10.3 Rio, FPC 3.0.4, как указано на гитхабе

Так у меня FPC 3.0.4 Где этот модуль искать?



--- Добавлено в 2021-11-16 00:45:03

Скачал последнюю версию lazarus всё равно не хочет работать.



Редактировалось 1 раз(а), последний 2021-11-16 00:45:03
карма: 1

0
Ответов: 4620
Рейтинг: 746
#4: 2021-11-16 12:39:15 ЛС | профиль | цитата
Заменить в кодах "Winapi.Windows" на просто "Windows". В остальных подобных случаях - аналогично.
карма: 26

0
Ответов: 2057
Рейтинг: 28
#5: 2021-11-16 15:53:39 ЛС | профиль | цитата
Netspirit писал(а):
Заменить в кодах "Winapi.Windows" на просто "Windows". В остальных подобных случаях - аналогично.

Да помогло, спасибо.

Теперь другая беда. Компилятор ругается на frame_number Вот скрин и код. Как я понимаю это переменная не объявлена и из-за этого компилятор ругается. Правильно?

[spoiler=]

(*
* Copyright (c) 2001 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*)

program decode_video;

{$APPTYPE CONSOLE}

uses
Windows,
//Winapi.Windows,
SysUtils, //System.SysUtils,
ffmpeg_types,
libavcodec,
libavdevice,
libavfilter,
libavformat,
libavutil,
libpostproc,
libswresample,
libswscale;

const
INBUF_SIZE = 4096;

procedure pgm_save(buf: PByte; wrap, xsize, ysize: Integer; filename: string);
var
f: THandle;
i: Integer;
s: AnsiString;
begin
f := FileCreate(filename);
if f = INVALID_HANDLE_VALUE then
begin
Writeln(ErrOutput, Format('Could not open %s', [filename]));
ExitCode := 1;
Exit;
end;
s := AnsiString(Format('P5'#10'%d %d'#10'%d'#10, [xsize, ysize, 255]));
FileWrite(f, s[1], Length(s));
for i := 0 to ysize - 1 do
FileWrite(f, PByte(PAnsiChar(buf) + i * wrap)^, xsize);
FileClose(f);
end;

function decode(dec_ctx: PAVCodecContext; frame: PAVFrame; pkt: PAVPacket; const filename: string): Boolean;
var
outfile: string;
ret: Integer;
begin
ret := avcodec_send_packet(dec_ctx, pkt);
if ret < 0 then
begin
Writeln(ErrOutput, 'Error sending a packet for decoding');
Result := False;
Exit;
end;

while ret >= 0 do
begin
ret := avcodec_receive_frame(dec_ctx, frame);
if (ret = AVERROR_EAGAIN) or (ret = AVERROR_EOF) then
begin
Result := True;
Exit;
end
else if ret < 0 then
begin
Writeln(ErrOutput, 'Error during decoding');
Result := False;
Exit;
end;

Writeln(Format('saving %sframe %3d', [dec_ctx.frame_number]));
// fflush(stdout);

(* the picture is allocated by the decoder, no need to free it *)
outfile := ChangeFileExt(filename, '');
pgm_save(@frame.data[0], frame.linesize[0], frame.width, frame.height, Format('%s-%d%s', [outfile, dec_ctx.frame_number, ExtractFileExt(filename)]));
end;
Result := True;
end;

function main(): Integer;
var
filename, outfilename: string;
codec: PAVCodec;
parser: PAVCodecParserContext;
c: PAVCodecContext;
f: THandle;
frame: PAVFrame;
inbuf: array [0 .. INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE - 1] of Byte;
data: puint8_t;
data_size: Cardinal;
ret: Integer;
pkt: PAVPacket;
begin
if ParamCount < 2 then
begin
Writeln(Format('Usage: %s <input file> <output file>', [ExtractFileName(ParamStr(0))]));
Result := 1;
Exit;
end;
filename := ParamStr(1);
outfilename := ParamStr(2);

avcodec_register_all();

pkt := av_packet_alloc();
if not Assigned(pkt) then
begin
Result := 1;
Exit;
end;

(* set end of buffer to 0 (this ensures that no overreading happens for damaged MPEG streams) *)
FillChar(inbuf[INBUF_SIZE], AV_INPUT_BUFFER_PADDING_SIZE, 0);

(* find the MPEG1 video decoder *)
codec := avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);
if not Assigned(codec) then
begin
Writeln(ErrOutput, 'Codec not found');
Result := 1;
Exit;
end;

parser := av_parser_init(Ord(codec.id));
if not Assigned(parser) then
begin
Writeln(ErrOutput, 'parser not found');
Result := 1;
Exit;
end;

c := avcodec_alloc_context3(codec);
if not Assigned(c) then
begin
Writeln(ErrOutput, 'Could not allocate video codec context');
Result := 1;
Exit;
end;

(* For some codecs, such as msmpeg4 and mpeg4, width and height
MUST be initialized there because this information is not
available in the bitstream. *)

(* open it *)
if avcodec_open2(c, codec, nil) < 0 then
begin
Writeln(ErrOutput, 'Could not open codec');
Result := 1;
Exit;
end;

f := FileOpen(filename, fmOpenRead);
if f = INVALID_HANDLE_VALUE then
begin
Writeln(ErrOutput, Format('Could not open %s', [filename]));
Result := 1;
Exit;
end;

frame := av_frame_alloc();
if not Assigned(frame) then
begin
Writeln(ErrOutput, 'Could not allocate video frame');
Result := 1;
Exit;
end;

while True do // not feof(f)
begin
(* read raw data from the input file *)
data_size := FileRead(f, inbuf[0], INBUF_SIZE);
if data_size = 0 then
Break;

(* use the parser to split the data into frames *)
data := @inbuf[0];
while data_size > 0 do
begin
ret := av_parser_parse2(parser, c, pkt.data, pkt.size, data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
if ret < 0 then
begin
Writeln(ErrOutput, 'Error while parsing');
Result := 1;
Exit;
end;
Inc(data, ret);
Dec(data_size, ret);

if pkt.size <> 0 then
if not decode(c, frame, pkt, outfilename) then
begin
Result := 1;
Exit;
end;
end;
end;
Result := 0;

(* flush the decoder *)
if not decode(c, frame, nil, outfilename) then
Result := 1;

FileClose(f);

av_parser_close(parser);
avcodec_free_context(c);
av_frame_free(frame);
av_packet_free(pkt);
end;

begin
try
ExitCode := main();
except
on E: Exception do
Writeln(ErrOutput, E.ClassName, ': ', E.Message);
end;

end.
[/spoiler]
Лазарус ошибка 1.png

--- Добавлено в 2021-11-16 16:31:32

Я скачал немного другие исходники и они компилируются. Буду разбираться с новыми исходниками.

Редактировалось 1 раз(а), последний 2021-11-16 16:31:32
карма: 1

0
Ответов: 207
Рейтинг: 14
#6: 2021-11-16 16:32:13 ЛС | профиль | цитата
Эдик, Без проблем компилируется.
карма: 2

0
Ответов: 2057
Рейтинг: 28
#7: 2021-11-16 16:51:47 ЛС | профиль | цитата
Joiner писал(а):
Эдик, Без проблем компилируется.

Похоже что то с компьютером у меня не то. Наверно какие то настройки сбились.
карма: 1

0
Ответов: 2057
Рейтинг: 28
#8: 2021-11-16 18:16:01 ЛС | профиль | цитата
Я тут скачал примеры програм для работы с FFMPEG и не могу сообразить что это за программы. При запуске появляется консель и пропадает. Поставил
readln;
что бы посмотреть, но нечего в консоле не увидел.
Как я понял это просто набор функций которые надо копировать и вставлять в свою программу. А программа сама по себе не чего не делает.
Вот код
(*
* Copyright (c) 2011 Reinhard Tartler
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*)

(**
* @file
* Shows how the metadata API can be used in application programs.
* @example metadata.c
*)

(*
* FFVCL - Delphi FFmpeg VCL Components
* http://www.DelphiFFmpeg.com
*
* Original file: doc/examples/metadata.c
* Ported by CodeCoolie@CNSW 2014/08/29 -> $Date:: 2021-02-22 #$
*)

(*
FFmpeg Delphi/Pascal Headers and Examples License Agreement

A modified part of FFVCL - Delphi FFmpeg VCL Components.
Copyright (c) 2008-2021 DelphiFFmpeg.com
All rights reserved.
http://www.DelphiFFmpeg.com

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

This source code is provided "as is" by DelphiFFmpeg.com without
warranty of any kind, either expressed or implied, including but not
limited to the implied warranties of merchantability and/or fitness
for a particular purpose.

Please also notice the License agreement of FFmpeg libraries.
*)

program metadata;

{$APPTYPE CONSOLE}

{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}

uses
{$IFDEF FPC}
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
SysUtils,
{$ELSE}
{$IF CompilerVersion >= 23.0}
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.SysUtils,
{$ELSE}
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
SysUtils,
{$IFEND}
{$ENDIF}

{$I headers.inc}
FFUtils;

function main(): Integer;
var
fmt_ctx: PAVFormatContext;
tag: PAVDictionaryEntry;
ret: Integer;
begin
fmt_ctx := nil;
tag := nil;

if ParamCount <> 1 then
begin
Writeln(ErrOutput, Format('usage: %s <input_file>' + sLineBreak +
'example program to demonstrate the use of the libavformat metadata API.',
[ExtractFileName(ParamStr(0))]));
Result := 1;
Exit;
end;

ret := avformat_open_input(@fmt_ctx, PAnsiChar(AnsiString(ParamStr(1))), nil, nil);
if ret < 0 then
begin
Writeln(ErrOutput, Format('Could not open %s', [ParamStr(1)]));
Result := ret;
Exit;
end;

ret := avformat_find_stream_info(fmt_ctx, nil);
if ret < 0 then
begin
Writeln(ErrOutput, 'Cannot find stream information');
Result := ret;
Exit;
end;

while True do
begin
tag := av_dict_get(fmt_ctx.metadata, '', tag, AV_DICT_IGNORE_SUFFIX);
if Assigned(tag) then
Writeln(Format('%s=%s', [string(tag.key), string(tag.value)]))
else
Break;
end;

avformat_close_input(@fmt_ctx);
Result := 0;
end;

begin
try
ExitCode := main();
except
on E: Exception do
Writeln(ErrOutput, E.ClassName, ': ', E.Message);
end;
end.

Я правильно понимаю?

Редактировалось 1 раз(а), последний 2021-11-16 18:17:01
карма: 1

0
Ответов: 4620
Рейтинг: 746
#9: 2021-11-17 13:12:40 ЛС | профиль | цитата
Это демки. Которые принимают параметры в командной строке и выдают какие-либо результаты туда же (что принимают, что выдают - надо смотреть описание). Для того чтобы видеть что пишет в консоль - запусти "Командную строку" Windows и запускай примеры оттуда - вставляешь полный путь к *.exe файлу и параметры командной строки.

Обычно оно в командной строке выводит список параметров. 'usage: %s <input_file>' напишет тебе в командной строке что-то вроде "usage: example.exe <input_file>".
Соответственно, ты в командной строке пишешь
"полный\путь\к\example.exe" "полный\путь\к\файлу.avi"

получаешь то, для чего предназначен пример.

Редактировалось 2 раз(а), последний 2021-11-17 13:16:35
карма: 26

0
Ответов: 2057
Рейтинг: 28
#10: 2021-11-17 18:15:47 ЛС | профиль | цитата
Joiner писал(а):
Эдик, Без проблем компилируется.

Раньше я компилировал своим способом и у меня не получалось. Попробовал твоим способом откомпилировать и получилось. Спасибо.

Редактировалось 3 раз(а), последний 2021-12-01 20:39:23
карма: 1

0
Ответов: 2057
Рейтинг: 28
#11: 2021-12-01 20:40:57 ЛС | профиль | цитата
Joiner писал(а):
Эдик, Без проблем компилируется.

Раньше я компилировал своим способом и у меня не получалось. Попробовал твоим способом откомпилировать и получилось. Спасибо.

Форум глючит. Не могу нормально отправить сообщение.
карма: 1

0
Ответов: 2057
Рейтинг: 28
#12: 2021-12-04 03:32:07 ЛС | профиль | цитата
Почему когда я ввожу код в lazarus у меня не выскакивают подсказки для автоматического завершения кода? Пробовал нажимать на разные галки в параметрах не помогло. Может вы знаете что надо включить?
Вот что я выделил на картинке вот этого у меня нет.
Подсказки.png
карма: 1

0
Ответов: 2057
Рейтинг: 28
#13: 2021-12-04 22:08:44 ЛС | профиль | цитата
В некоторых местах появляется подсказка, а в некоторых нет.
карма: 1

0
Ответов: 4620
Рейтинг: 746
#14: 2021-12-06 17:55:12 ЛС | профиль | цитата
Модули, в которых лежат требуемые функции (для подсказок), должны быть скомпилированы с отладочной информацией.
Может быть две версии скомпилированных системных модулей: Debug, Release.
В свойствах проекта должна быть указана опция "Use debug units" (если она есть). А в настройках IDE "Debug DCU Path" должен содержать путь к папкам с debug модулями.
Проект тоже может быть скомпилирован с debug информацией или без. Вот в настройках проекта в конфигурации debug нужно включить отладочную информацию и "Use debug units".

Это применительно к Delphi, в Lazarus должно быть что-то подобное.
карма: 26

0
Ответов: 963
Рейтинг: 12
#15: 2021-12-08 00:04:54 ЛС | профиль | цитата
Эдик писал(а):
В некоторых местах появляется подсказка, а в некоторых нет.

Просто нужно точку поставить и немного подождать, если подложишь дальше быстро набрать код подсказка не впадает.

Но там есть еще одна тонкость: Если поставить точку после идентификатора класса то все будет нормально (выпадет локальный список методов и свойства конкретного класса ) но если поставить точку просто где-то между begin и end то выпадет некий "глобальный список " всех имен в программе (тоже самое происходит если в имени идентификатора "составного типа"(рекорд,обджект,клаасс) допущена ошибка ). Из за этого может быть путаница. Но глобальный список может помочь если например нужно вспомнить имя модуля или глобальной переменной.
(Правда потом "лишнюю точку" нужно удалять вручную (возможно разрабы Лазаруса чуть схалтурили, а может решили что так надежнее ) но это уже "мелочи жизни" )

Редактировалось 11 раз(а), последний 2021-12-08 00:28:47
карма: 0

0
Сообщение
...
Прикрепленные файлы
(файлы не залиты)