code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * frame CRC encoder (for codec/format testing) * Copyright (c) 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/adler32.h" #include "avformat.h" static int framecrc_write_packet(struct AVFormatContext *s, AVPacket *pkt) { uint32_t crc = av_adler32_update(0, pkt->data, pkt->size); char buf[256]; snprintf(buf, sizeof(buf), "%d, %"PRId64", %d, 0x%08x\n", pkt->stream_index, pkt->dts, pkt->size, crc); put_buffer(s->pb, buf, strlen(buf)); put_flush_packet(s->pb); return 0; } AVOutputFormat framecrc_muxer = { "framecrc", NULL_IF_CONFIG_SMALL("framecrc testing format"), NULL, "", 0, CODEC_ID_PCM_S16LE, CODEC_ID_RAWVIDEO, NULL, framecrc_write_packet, NULL, };
123linslouis-android-video-cutter
jni/libavformat/framecrcenc.c
C
asf20
1,487
/* * ID3v2 header parser * Copyright (c) 2003 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "id3v2.h" #include "id3v1.h" #include "libavutil/avstring.h" int ff_id3v2_match(const uint8_t *buf) { return buf[0] == 'I' && buf[1] == 'D' && buf[2] == '3' && buf[3] != 0xff && buf[4] != 0xff && (buf[6] & 0x80) == 0 && (buf[7] & 0x80) == 0 && (buf[8] & 0x80) == 0 && (buf[9] & 0x80) == 0; } int ff_id3v2_tag_len(const uint8_t * buf) { int len = ((buf[6] & 0x7f) << 21) + ((buf[7] & 0x7f) << 14) + ((buf[8] & 0x7f) << 7) + (buf[9] & 0x7f) + ID3v2_HEADER_SIZE; if (buf[5] & 0x10) len += ID3v2_HEADER_SIZE; return len; } void ff_id3v2_read(AVFormatContext *s) { int len, ret; uint8_t buf[ID3v2_HEADER_SIZE]; ret = get_buffer(s->pb, buf, ID3v2_HEADER_SIZE); if (ret != ID3v2_HEADER_SIZE) return; if (ff_id3v2_match(buf)) { /* parse ID3v2 header */ len = ((buf[6] & 0x7f) << 21) | ((buf[7] & 0x7f) << 14) | ((buf[8] & 0x7f) << 7) | (buf[9] & 0x7f); ff_id3v2_parse(s, len, buf[3], buf[5]); } else { url_fseek(s->pb, 0, SEEK_SET); } } static unsigned int get_size(ByteIOContext *s, int len) { int v = 0; while (len--) v = (v << 7) + (get_byte(s) & 0x7F); return v; } static void read_ttag(AVFormatContext *s, int taglen, const char *key) { char *q, dst[512]; const char *val = NULL; int len, dstlen = sizeof(dst) - 1; unsigned genre; unsigned int (*get)(ByteIOContext*) = get_be16; dst[0] = 0; if (taglen < 1) return; taglen--; /* account for encoding type byte */ switch (get_byte(s->pb)) { /* encoding type */ case 0: /* ISO-8859-1 (0 - 255 maps directly into unicode) */ q = dst; while (taglen-- && q - dst < dstlen - 7) { uint8_t tmp; PUT_UTF8(get_byte(s->pb), tmp, *q++ = tmp;) } *q = 0; break; case 1: /* UTF-16 with BOM */ taglen -= 2; switch (get_be16(s->pb)) { case 0xfffe: get = get_le16; case 0xfeff: break; default: av_log(s, AV_LOG_ERROR, "Incorrect BOM value in tag %s.\n", key); return; } // fall-through case 2: /* UTF-16BE without BOM */ q = dst; while (taglen > 1 && q - dst < dstlen - 7) { uint32_t ch; uint8_t tmp; GET_UTF16(ch, ((taglen -= 2) >= 0 ? get(s->pb) : 0), break;) PUT_UTF8(ch, tmp, *q++ = tmp;) } *q = 0; break; case 3: /* UTF-8 */ len = FFMIN(taglen, dstlen); get_buffer(s->pb, dst, len); dst[len] = 0; break; default: av_log(s, AV_LOG_WARNING, "Unknown encoding in tag %s\n.", key); } if (!(strcmp(key, "TCON") && strcmp(key, "TCO")) && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1) && genre <= ID3v1_GENRE_MAX) val = ff_id3v1_genre_str[genre]; else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) { /* dst now contains two 0-terminated strings */ dst[dstlen] = 0; len = strlen(dst); key = dst; val = dst + FFMIN(len + 1, dstlen); } else if (*dst) val = dst; if (val) av_metadata_set2(&s->metadata, key, val, 0); } void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags) { int isv34, tlen; char tag[5]; int64_t next; int taghdrlen; const char *reason; switch (version) { case 2: if (flags & 0x40) { reason = "compression"; goto error; } isv34 = 0; taghdrlen = 6; break; case 3: case 4: isv34 = 1; taghdrlen = 10; break; default: reason = "version"; goto error; } if (flags & 0x80) { reason = "unsynchronization"; goto error; } if (isv34 && flags & 0x40) /* Extended header present, just skip over it */ url_fskip(s->pb, get_size(s->pb, 4)); while (len >= taghdrlen) { if (isv34) { get_buffer(s->pb, tag, 4); tag[4] = 0; if(version==3){ tlen = get_be32(s->pb); }else tlen = get_size(s->pb, 4); get_be16(s->pb); /* flags */ } else { get_buffer(s->pb, tag, 3); tag[3] = 0; tlen = get_be24(s->pb); } len -= taghdrlen + tlen; if (len < 0) break; next = url_ftell(s->pb) + tlen; if (tag[0] == 'T') read_ttag(s, tlen, tag); else if (!tag[0]) { if (tag[1]) av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding"); url_fskip(s->pb, len); break; } /* Skip to end of tag */ url_fseek(s->pb, next, SEEK_SET); } if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */ url_fskip(s->pb, 10); return; error: av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason); url_fskip(s->pb, len); } const AVMetadataConv ff_id3v2_metadata_conv[] = { { "TALB", "album"}, { "TAL", "album"}, { "TCOM", "composer"}, { "TCON", "genre"}, { "TCO", "genre"}, { "TCOP", "copyright"}, { "TDRL", "date"}, { "TDRC", "date"}, { "TENC", "encoded_by"}, { "TEN", "encoded_by"}, { "TIT2", "title"}, { "TT2", "title"}, { "TLAN", "language"}, { "TPE1", "artist"}, { "TP1", "artist"}, { "TPE2", "album_artist"}, { "TP2", "album_artist"}, { "TPE3", "performer"}, { "TP3", "performer"}, { "TPOS", "disc"}, { "TPUB", "publisher"}, { "TRCK", "track"}, { "TRK", "track"}, { "TSOA", "album-sort"}, { "TSOP", "artist-sort"}, { "TSOT", "title-sort"}, { "TSSE", "encoder"}, { 0 } }; const char ff_id3v2_tags[][4] = { "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDEN", "TDLY", "TDOR", "TDRC", "TDRL", "TDTG", "TENC", "TEXT", "TFLT", "TIPL", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMCL", "TMED", "TMOO", "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3", "TPE4", "TPOS", "TPRO", "TPUB", "TRCK", "TRSN", "TRSO", "TSOA", "TSOP", "TSOT", "TSRC", "TSSE", "TSST", { 0 }, };
123linslouis-android-video-cutter
jni/libavformat/id3v2.c
C
asf20
7,411
/* * AVISynth support for ffmpeg system * Copyright (c) 2006 DivX, Inc. * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avformat.h" #include "riff.h" #include <windows.h> #include <vfw.h> typedef struct { PAVISTREAM handle; AVISTREAMINFO info; DWORD read; LONG chunck_size; LONG chunck_samples; } AVISynthStream; typedef struct { PAVIFILE file; AVISynthStream *streams; int nb_streams; int next_stream; } AVISynthContext; static int avisynth_read_header(AVFormatContext *s, AVFormatParameters *ap) { AVISynthContext *avs = s->priv_data; HRESULT res; AVIFILEINFO info; DWORD id; AVStream *st; AVISynthStream *stream; AVIFileInit(); res = AVIFileOpen(&avs->file, s->filename, OF_READ|OF_SHARE_DENY_WRITE, NULL); if (res != S_OK) { av_log(s, AV_LOG_ERROR, "AVIFileOpen failed with error %ld", res); AVIFileExit(); return -1; } res = AVIFileInfo(avs->file, &info, sizeof(info)); if (res != S_OK) { av_log(s, AV_LOG_ERROR, "AVIFileInfo failed with error %ld", res); AVIFileExit(); return -1; } avs->streams = av_mallocz(info.dwStreams * sizeof(AVISynthStream)); for (id=0; id<info.dwStreams; id++) { stream = &avs->streams[id]; stream->read = 0; if (AVIFileGetStream(avs->file, &stream->handle, 0, id) == S_OK) { if (AVIStreamInfo(stream->handle, &stream->info, sizeof(stream->info)) == S_OK) { if (stream->info.fccType == streamtypeAUDIO) { WAVEFORMATEX wvfmt; LONG struct_size = sizeof(WAVEFORMATEX); if (AVIStreamReadFormat(stream->handle, 0, &wvfmt, &struct_size) != S_OK) continue; st = av_new_stream(s, id); st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->block_align = wvfmt.nBlockAlign; st->codec->channels = wvfmt.nChannels; st->codec->sample_rate = wvfmt.nSamplesPerSec; st->codec->bit_rate = wvfmt.nAvgBytesPerSec * 8; st->codec->bits_per_coded_sample = wvfmt.wBitsPerSample; stream->chunck_samples = wvfmt.nSamplesPerSec * (uint64_t)info.dwScale / (uint64_t)info.dwRate; stream->chunck_size = stream->chunck_samples * wvfmt.nChannels * wvfmt.wBitsPerSample / 8; st->codec->codec_tag = wvfmt.wFormatTag; st->codec->codec_id = ff_wav_codec_get_id(wvfmt.wFormatTag, st->codec->bits_per_coded_sample); } else if (stream->info.fccType == streamtypeVIDEO) { BITMAPINFO imgfmt; LONG struct_size = sizeof(BITMAPINFO); stream->chunck_size = stream->info.dwSampleSize; stream->chunck_samples = 1; if (AVIStreamReadFormat(stream->handle, 0, &imgfmt, &struct_size) != S_OK) continue; st = av_new_stream(s, id); st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->r_frame_rate.num = stream->info.dwRate; st->r_frame_rate.den = stream->info.dwScale; st->codec->width = imgfmt.bmiHeader.biWidth; st->codec->height = imgfmt.bmiHeader.biHeight; st->codec->bits_per_coded_sample = imgfmt.bmiHeader.biBitCount; st->codec->bit_rate = (uint64_t)stream->info.dwSampleSize * (uint64_t)stream->info.dwRate * 8 / (uint64_t)stream->info.dwScale; st->codec->codec_tag = imgfmt.bmiHeader.biCompression; st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, imgfmt.bmiHeader.biCompression); st->duration = stream->info.dwLength; } else { AVIStreamRelease(stream->handle); continue; } avs->nb_streams++; st->codec->stream_codec_tag = stream->info.fccHandler; av_set_pts_info(st, 64, info.dwScale, info.dwRate); st->start_time = stream->info.dwStart; } } } return 0; } static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt) { AVISynthContext *avs = s->priv_data; HRESULT res; AVISynthStream *stream; int stream_id = avs->next_stream; LONG read_size; // handle interleaving manually... stream = &avs->streams[stream_id]; if (stream->read >= stream->info.dwLength) return AVERROR(EIO); if (av_new_packet(pkt, stream->chunck_size)) return AVERROR(EIO); pkt->stream_index = stream_id; pkt->pts = avs->streams[stream_id].read / avs->streams[stream_id].chunck_samples; res = AVIStreamRead(stream->handle, stream->read, stream->chunck_samples, pkt->data, stream->chunck_size, &read_size, NULL); pkt->pts = stream->read; pkt->size = read_size; stream->read += stream->chunck_samples; // prepare for the next stream to read do { avs->next_stream = (avs->next_stream+1) % avs->nb_streams; } while (avs->next_stream != stream_id && s->streams[avs->next_stream]->discard >= AVDISCARD_ALL); return (res == S_OK) ? pkt->size : -1; } static int avisynth_read_close(AVFormatContext *s) { AVISynthContext *avs = s->priv_data; int i; for (i=0;i<avs->nb_streams;i++) { AVIStreamRelease(avs->streams[i].handle); } av_free(avs->streams); AVIFileRelease(avs->file); AVIFileExit(); return 0; } static int avisynth_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags) { AVISynthContext *avs = s->priv_data; int stream_id; for (stream_id = 0; stream_id < avs->nb_streams; stream_id++) { avs->streams[stream_id].read = pts * avs->streams[stream_id].chunck_samples; } return 0; } AVInputFormat avisynth_demuxer = { "avs", NULL_IF_CONFIG_SMALL("AVISynth"), sizeof(AVISynthContext), NULL, avisynth_read_header, avisynth_read_packet, avisynth_read_close, avisynth_read_seek, NULL, 0, "avs", };
123linslouis-android-video-cutter
jni/libavformat/avisynth.c
C
asf20
6,850
/* * RTMP network protocol * Copyright (c) 2009 Kostya Shishkov * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * RTMP protocol */ #include "libavcodec/bytestream.h" #include "libavutil/avstring.h" #include "libavutil/lfg.h" #include "libavutil/sha.h" #include "avformat.h" #include "internal.h" #include "network.h" #include "flv.h" #include "rtmp.h" #include "rtmppkt.h" /* we can't use av_log() with URLContext yet... */ #if LIBAVFORMAT_VERSION_MAJOR < 53 #define LOG_CONTEXT NULL #else #define LOG_CONTEXT s #endif //#define DEBUG /** RTMP protocol handler state */ typedef enum { STATE_START, ///< client has not done anything yet STATE_HANDSHAKED, ///< client has performed handshake STATE_RELEASING, ///< client releasing stream before publish it (for output) STATE_FCPUBLISH, ///< client FCPublishing stream (for output) STATE_CONNECTING, ///< client connected to server successfully STATE_READY, ///< client has sent all needed commands and waits for server reply STATE_PLAYING, ///< client has started receiving multimedia data from server STATE_PUBLISHING, ///< client has started sending multimedia data to server (for output) STATE_STOPPED, ///< the broadcast has been stopped } ClientState; /** protocol handler context */ typedef struct RTMPContext { URLContext* stream; ///< TCP stream used in interactions with RTMP server RTMPPacket prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets int chunk_size; ///< size of the chunks RTMP packets are divided into int is_input; ///< input/output flag char playpath[256]; ///< path to filename to play (with possible "mp4:" prefix) char app[128]; ///< application ClientState state; ///< current state int main_channel_id; ///< an additional channel ID which is used for some invocations uint8_t* flv_data; ///< buffer with data for demuxer int flv_size; ///< current buffer size int flv_off; ///< number of bytes read from current buffer RTMPPacket out_pkt; ///< rtmp packet, created from flv a/v or metadata (for output) uint32_t client_report_size; ///< number of bytes after which client should report to server uint32_t bytes_read; ///< number of bytes read from server uint32_t last_bytes_read; ///< number of bytes read last reported to server } RTMPContext; #define PLAYER_KEY_OPEN_PART_LEN 30 ///< length of partial key used for first client digest signing /** Client key used for digest signing */ static const uint8_t rtmp_player_key[] = { 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ', 'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1', 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02, 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8, 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE }; #define SERVER_KEY_OPEN_PART_LEN 36 ///< length of partial key used for first server digest signing /** Key used for RTMP server digest signing */ static const uint8_t rtmp_server_key[] = { 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ', 'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ', 'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1', 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02, 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8, 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE }; /** * Generates 'connect' call and sends it to the server. */ static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto, const char *host, int port) { RTMPPacket pkt; uint8_t ver[64], *p; char tcurl[512]; ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 4096); p = pkt.data; ff_url_join(tcurl, sizeof(tcurl), proto, NULL, host, port, "/%s", rt->app); ff_amf_write_string(&p, "connect"); ff_amf_write_number(&p, 1.0); ff_amf_write_object_start(&p); ff_amf_write_field_name(&p, "app"); ff_amf_write_string(&p, rt->app); if (rt->is_input) { snprintf(ver, sizeof(ver), "%s %d,%d,%d,%d", RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1, RTMP_CLIENT_VER2, RTMP_CLIENT_VER3, RTMP_CLIENT_VER4); } else { snprintf(ver, sizeof(ver), "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT); ff_amf_write_field_name(&p, "type"); ff_amf_write_string(&p, "nonprivate"); } ff_amf_write_field_name(&p, "flashVer"); ff_amf_write_string(&p, ver); ff_amf_write_field_name(&p, "tcUrl"); ff_amf_write_string(&p, tcurl); if (rt->is_input) { ff_amf_write_field_name(&p, "fpad"); ff_amf_write_bool(&p, 0); ff_amf_write_field_name(&p, "capabilities"); ff_amf_write_number(&p, 15.0); ff_amf_write_field_name(&p, "audioCodecs"); ff_amf_write_number(&p, 1639.0); ff_amf_write_field_name(&p, "videoCodecs"); ff_amf_write_number(&p, 252.0); ff_amf_write_field_name(&p, "videoFunction"); ff_amf_write_number(&p, 1.0); } ff_amf_write_object_end(&p); pkt.data_size = p - pkt.data; ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } /** * Generates 'releaseStream' call and sends it to the server. It should make * the server release some channel for media streams. */ static void gen_release_stream(URLContext *s, RTMPContext *rt) { RTMPPacket pkt; uint8_t *p; ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 29 + strlen(rt->playpath)); av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Releasing stream...\n"); p = pkt.data; ff_amf_write_string(&p, "releaseStream"); ff_amf_write_number(&p, 2.0); ff_amf_write_null(&p); ff_amf_write_string(&p, rt->playpath); ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } /** * Generates 'FCPublish' call and sends it to the server. It should make * the server preapare for receiving media streams. */ static void gen_fcpublish_stream(URLContext *s, RTMPContext *rt) { RTMPPacket pkt; uint8_t *p; ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 25 + strlen(rt->playpath)); av_log(LOG_CONTEXT, AV_LOG_DEBUG, "FCPublish stream...\n"); p = pkt.data; ff_amf_write_string(&p, "FCPublish"); ff_amf_write_number(&p, 3.0); ff_amf_write_null(&p); ff_amf_write_string(&p, rt->playpath); ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } /** * Generates 'FCUnpublish' call and sends it to the server. It should make * the server destroy stream. */ static void gen_fcunpublish_stream(URLContext *s, RTMPContext *rt) { RTMPPacket pkt; uint8_t *p; ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 27 + strlen(rt->playpath)); av_log(LOG_CONTEXT, AV_LOG_DEBUG, "UnPublishing stream...\n"); p = pkt.data; ff_amf_write_string(&p, "FCUnpublish"); ff_amf_write_number(&p, 5.0); ff_amf_write_null(&p); ff_amf_write_string(&p, rt->playpath); ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } /** * Generates 'createStream' call and sends it to the server. It should make * the server allocate some channel for media streams. */ static void gen_create_stream(URLContext *s, RTMPContext *rt) { RTMPPacket pkt; uint8_t *p; av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Creating stream...\n"); ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 25); p = pkt.data; ff_amf_write_string(&p, "createStream"); ff_amf_write_number(&p, rt->is_input ? 3.0 : 4.0); ff_amf_write_null(&p); ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } /** * Generates 'deleteStream' call and sends it to the server. It should make * the server remove some channel for media streams. */ static void gen_delete_stream(URLContext *s, RTMPContext *rt) { RTMPPacket pkt; uint8_t *p; av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Deleting stream...\n"); ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 34); p = pkt.data; ff_amf_write_string(&p, "deleteStream"); ff_amf_write_number(&p, 0.0); ff_amf_write_null(&p); ff_amf_write_number(&p, rt->main_channel_id); ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } /** * Generates 'play' call and sends it to the server, then pings the server * to start actual playing. */ static void gen_play(URLContext *s, RTMPContext *rt) { RTMPPacket pkt; uint8_t *p; av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath); ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0, 20 + strlen(rt->playpath)); pkt.extra = rt->main_channel_id; p = pkt.data; ff_amf_write_string(&p, "play"); ff_amf_write_number(&p, 0.0); ff_amf_write_null(&p); ff_amf_write_string(&p, rt->playpath); ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); // set client buffer time disguised in ping packet ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, 1, 10); p = pkt.data; bytestream_put_be16(&p, 3); bytestream_put_be32(&p, 1); bytestream_put_be32(&p, 256); //TODO: what is a good value here? ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } /** * Generates 'publish' call and sends it to the server. */ static void gen_publish(URLContext *s, RTMPContext *rt) { RTMPPacket pkt; uint8_t *p; av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending publish command for '%s'\n", rt->playpath); ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE, 0, 30 + strlen(rt->playpath)); pkt.extra = rt->main_channel_id; p = pkt.data; ff_amf_write_string(&p, "publish"); ff_amf_write_number(&p, 0.0); ff_amf_write_null(&p); ff_amf_write_string(&p, rt->playpath); ff_amf_write_string(&p, "live"); ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } /** * Generates ping reply and sends it to the server. */ static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt) { RTMPPacket pkt; uint8_t *p; ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, ppkt->timestamp + 1, 6); p = pkt.data; bytestream_put_be16(&p, 7); bytestream_put_be32(&p, AV_RB32(ppkt->data+2)); ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } /** * Generates report on bytes read so far and sends it to the server. */ static void gen_bytes_read(URLContext *s, RTMPContext *rt, uint32_t ts) { RTMPPacket pkt; uint8_t *p; ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_BYTES_READ, ts, 4); p = pkt.data; bytestream_put_be32(&p, rt->bytes_read); ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&pkt); } //TODO: Move HMAC code somewhere. Eventually. #define HMAC_IPAD_VAL 0x36 #define HMAC_OPAD_VAL 0x5C /** * Calculates HMAC-SHA2 digest for RTMP handshake packets. * * @param src input buffer * @param len input buffer length (should be 1536) * @param gap offset in buffer where 32 bytes should not be taken into account * when calculating digest (since it will be used to store that digest) * @param key digest key * @param keylen digest key length * @param dst buffer where calculated digest will be stored (32 bytes) */ static void rtmp_calc_digest(const uint8_t *src, int len, int gap, const uint8_t *key, int keylen, uint8_t *dst) { struct AVSHA *sha; uint8_t hmac_buf[64+32] = {0}; int i; sha = av_mallocz(av_sha_size); if (keylen < 64) { memcpy(hmac_buf, key, keylen); } else { av_sha_init(sha, 256); av_sha_update(sha,key, keylen); av_sha_final(sha, hmac_buf); } for (i = 0; i < 64; i++) hmac_buf[i] ^= HMAC_IPAD_VAL; av_sha_init(sha, 256); av_sha_update(sha, hmac_buf, 64); if (gap <= 0) { av_sha_update(sha, src, len); } else { //skip 32 bytes used for storing digest av_sha_update(sha, src, gap); av_sha_update(sha, src + gap + 32, len - gap - 32); } av_sha_final(sha, hmac_buf + 64); for (i = 0; i < 64; i++) hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad av_sha_init(sha, 256); av_sha_update(sha, hmac_buf, 64+32); av_sha_final(sha, dst); av_free(sha); } /** * Puts HMAC-SHA2 digest of packet data (except for the bytes where this digest * will be stored) into that packet. * * @param buf handshake data (1536 bytes) * @return offset to the digest inside input data */ static int rtmp_handshake_imprint_with_digest(uint8_t *buf) { int i, digest_pos = 0; for (i = 8; i < 12; i++) digest_pos += buf[i]; digest_pos = (digest_pos % 728) + 12; rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos, rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN, buf + digest_pos); return digest_pos; } /** * Verifies that the received server response has the expected digest value. * * @param buf handshake data received from the server (1536 bytes) * @param off position to search digest offset from * @return 0 if digest is valid, digest position otherwise */ static int rtmp_validate_digest(uint8_t *buf, int off) { int i, digest_pos = 0; uint8_t digest[32]; for (i = 0; i < 4; i++) digest_pos += buf[i + off]; digest_pos = (digest_pos % 728) + off + 4; rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos, rtmp_server_key, SERVER_KEY_OPEN_PART_LEN, digest); if (!memcmp(digest, buf + digest_pos, 32)) return digest_pos; return 0; } /** * Performs handshake with the server by means of exchanging pseudorandom data * signed with HMAC-SHA2 digest. * * @return 0 if handshake succeeds, negative value otherwise */ static int rtmp_handshake(URLContext *s, RTMPContext *rt) { AVLFG rnd; uint8_t tosend [RTMP_HANDSHAKE_PACKET_SIZE+1] = { 3, // unencrypted data 0, 0, 0, 0, // client uptime RTMP_CLIENT_VER1, RTMP_CLIENT_VER2, RTMP_CLIENT_VER3, RTMP_CLIENT_VER4, }; uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE]; uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1]; int i; int server_pos, client_pos; uint8_t digest[32]; av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Handshaking...\n"); av_lfg_init(&rnd, 0xDEADC0DE); // generate handshake packet - 1536 bytes of pseudorandom data for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++) tosend[i] = av_lfg_get(&rnd) >> 24; client_pos = rtmp_handshake_imprint_with_digest(tosend + 1); url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1); i = url_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1); if (i != RTMP_HANDSHAKE_PACKET_SIZE + 1) { av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n"); return -1; } i = url_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE); if (i != RTMP_HANDSHAKE_PACKET_SIZE) { av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n"); return -1; } av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n", serverdata[5], serverdata[6], serverdata[7], serverdata[8]); if (rt->is_input && serverdata[5] >= 3) { server_pos = rtmp_validate_digest(serverdata + 1, 772); if (!server_pos) { server_pos = rtmp_validate_digest(serverdata + 1, 8); if (!server_pos) { av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server response validating failed\n"); return -1; } } rtmp_calc_digest(tosend + 1 + client_pos, 32, 0, rtmp_server_key, sizeof(rtmp_server_key), digest); rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE-32, 0, digest, 32, digest); if (memcmp(digest, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) { av_log(LOG_CONTEXT, AV_LOG_ERROR, "Signature mismatch\n"); return -1; } for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++) tosend[i] = av_lfg_get(&rnd) >> 24; rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0, rtmp_player_key, sizeof(rtmp_player_key), digest); rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0, digest, 32, tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32); // write reply back to the server url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE); } else { url_write(rt->stream, serverdata+1, RTMP_HANDSHAKE_PACKET_SIZE); } return 0; } /** * Parses received packet and may perform some action depending on * the packet contents. * @return 0 for no errors, negative values for serious errors which prevent * further communications, positive values for uncritical errors */ static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt) { int i, t; const uint8_t *data_end = pkt->data + pkt->data_size; #ifdef DEBUG ff_rtmp_packet_dump(LOG_CONTEXT, pkt); #endif switch (pkt->type) { case RTMP_PT_CHUNK_SIZE: if (pkt->data_size != 4) { av_log(LOG_CONTEXT, AV_LOG_ERROR, "Chunk size change packet is not 4 bytes long (%d)\n", pkt->data_size); return -1; } if (!rt->is_input) ff_rtmp_packet_write(rt->stream, pkt, rt->chunk_size, rt->prev_pkt[1]); rt->chunk_size = AV_RB32(pkt->data); if (rt->chunk_size <= 0) { av_log(LOG_CONTEXT, AV_LOG_ERROR, "Incorrect chunk size %d\n", rt->chunk_size); return -1; } av_log(LOG_CONTEXT, AV_LOG_DEBUG, "New chunk size = %d\n", rt->chunk_size); break; case RTMP_PT_PING: t = AV_RB16(pkt->data); if (t == 6) gen_pong(s, rt, pkt); break; case RTMP_PT_CLIENT_BW: if (pkt->data_size < 4) { av_log(LOG_CONTEXT, AV_LOG_ERROR, "Client bandwidth report packet is less than 4 bytes long (%d)\n", pkt->data_size); return -1; } av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Client bandwidth = %d\n", AV_RB32(pkt->data)); rt->client_report_size = AV_RB32(pkt->data) >> 1; break; case RTMP_PT_INVOKE: //TODO: check for the messages sent for wrong state? if (!memcmp(pkt->data, "\002\000\006_error", 9)) { uint8_t tmpstr[256]; if (!ff_amf_get_field_value(pkt->data + 9, data_end, "description", tmpstr, sizeof(tmpstr))) av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr); return -1; } else if (!memcmp(pkt->data, "\002\000\007_result", 10)) { switch (rt->state) { case STATE_HANDSHAKED: if (!rt->is_input) { gen_release_stream(s, rt); gen_fcpublish_stream(s, rt); rt->state = STATE_RELEASING; } else { rt->state = STATE_CONNECTING; } gen_create_stream(s, rt); break; case STATE_FCPUBLISH: rt->state = STATE_CONNECTING; break; case STATE_RELEASING: rt->state = STATE_FCPUBLISH; /* hack for Wowza Media Server, it does not send result for * releaseStream and FCPublish calls */ if (!pkt->data[10]) { int pkt_id = (int) av_int2dbl(AV_RB64(pkt->data + 11)); if (pkt_id == 4) rt->state = STATE_CONNECTING; } if (rt->state != STATE_CONNECTING) break; case STATE_CONNECTING: //extract a number from the result if (pkt->data[10] || pkt->data[19] != 5 || pkt->data[20]) { av_log(LOG_CONTEXT, AV_LOG_WARNING, "Unexpected reply on connect()\n"); } else { rt->main_channel_id = (int) av_int2dbl(AV_RB64(pkt->data + 21)); } if (rt->is_input) { gen_play(s, rt); } else { gen_publish(s, rt); } rt->state = STATE_READY; break; } } else if (!memcmp(pkt->data, "\002\000\010onStatus", 11)) { const uint8_t* ptr = pkt->data + 11; uint8_t tmpstr[256]; for (i = 0; i < 2; i++) { t = ff_amf_tag_size(ptr, data_end); if (t < 0) return 1; ptr += t; } t = ff_amf_get_field_value(ptr, data_end, "level", tmpstr, sizeof(tmpstr)); if (!t && !strcmp(tmpstr, "error")) { if (!ff_amf_get_field_value(ptr, data_end, "description", tmpstr, sizeof(tmpstr))) av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr); return -1; } t = ff_amf_get_field_value(ptr, data_end, "code", tmpstr, sizeof(tmpstr)); if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) rt->state = STATE_PLAYING; if (!t && !strcmp(tmpstr, "NetStream.Play.Stop")) rt->state = STATE_STOPPED; if (!t && !strcmp(tmpstr, "NetStream.Play.UnpublishNotify")) rt->state = STATE_STOPPED; if (!t && !strcmp(tmpstr, "NetStream.Publish.Start")) rt->state = STATE_PUBLISHING; } break; } return 0; } /** * Interacts with the server by receiving and sending RTMP packets until * there is some significant data (media data or expected status notification). * * @param s reading context * @param for_header non-zero value tells function to work until it * gets notification from the server that playing has been started, * otherwise function will work until some media data is received (or * an error happens) * @return 0 for successful operation, negative value in case of error */ static int get_packet(URLContext *s, int for_header) { RTMPContext *rt = s->priv_data; int ret; uint8_t *p; const uint8_t *next; uint32_t data_size; uint32_t ts, cts, pts=0; if (rt->state == STATE_STOPPED) return AVERROR_EOF; for (;;) { RTMPPacket rpkt; if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt, rt->chunk_size, rt->prev_pkt[0])) <= 0) { if (ret == 0) { return AVERROR(EAGAIN); } else { return AVERROR(EIO); } } rt->bytes_read += ret; if (rt->bytes_read > rt->last_bytes_read + rt->client_report_size) { av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending bytes read report\n"); gen_bytes_read(s, rt, rpkt.timestamp + 1); rt->last_bytes_read = rt->bytes_read; } ret = rtmp_parse_result(s, rt, &rpkt); if (ret < 0) {//serious error in current packet ff_rtmp_packet_destroy(&rpkt); return -1; } if (rt->state == STATE_STOPPED) { ff_rtmp_packet_destroy(&rpkt); return AVERROR_EOF; } if (for_header && (rt->state == STATE_PLAYING || rt->state == STATE_PUBLISHING)) { ff_rtmp_packet_destroy(&rpkt); return 0; } if (!rpkt.data_size || !rt->is_input) { ff_rtmp_packet_destroy(&rpkt); continue; } if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO || (rpkt.type == RTMP_PT_NOTIFY && !memcmp("\002\000\012onMetaData", rpkt.data, 13))) { ts = rpkt.timestamp; // generate packet header and put data into buffer for FLV demuxer rt->flv_off = 0; rt->flv_size = rpkt.data_size + 15; rt->flv_data = p = av_realloc(rt->flv_data, rt->flv_size); bytestream_put_byte(&p, rpkt.type); bytestream_put_be24(&p, rpkt.data_size); bytestream_put_be24(&p, ts); bytestream_put_byte(&p, ts >> 24); bytestream_put_be24(&p, 0); bytestream_put_buffer(&p, rpkt.data, rpkt.data_size); bytestream_put_be32(&p, 0); ff_rtmp_packet_destroy(&rpkt); return 0; } else if (rpkt.type == RTMP_PT_METADATA) { // we got raw FLV data, make it available for FLV demuxer rt->flv_off = 0; rt->flv_size = rpkt.data_size; rt->flv_data = av_realloc(rt->flv_data, rt->flv_size); /* rewrite timestamps */ next = rpkt.data; ts = rpkt.timestamp; while (next - rpkt.data < rpkt.data_size - 11) { next++; data_size = bytestream_get_be24(&next); p=next; cts = bytestream_get_be24(&next); cts |= bytestream_get_byte(&next); if (pts==0) pts=cts; ts += cts - pts; pts = cts; bytestream_put_be24(&p, ts); bytestream_put_byte(&p, ts >> 24); next += data_size + 3 + 4; } memcpy(rt->flv_data, rpkt.data, rpkt.data_size); ff_rtmp_packet_destroy(&rpkt); return 0; } ff_rtmp_packet_destroy(&rpkt); } return 0; } static int rtmp_close(URLContext *h) { RTMPContext *rt = h->priv_data; if (!rt->is_input) { rt->flv_data = NULL; if (rt->out_pkt.data_size) ff_rtmp_packet_destroy(&rt->out_pkt); if (rt->state > STATE_FCPUBLISH) gen_fcunpublish_stream(h, rt); } if (rt->state > STATE_HANDSHAKED) gen_delete_stream(h, rt); av_freep(&rt->flv_data); url_close(rt->stream); av_free(rt); return 0; } /** * Opens RTMP connection and verifies that the stream can be played. * * URL syntax: rtmp://server[:port][/app][/playpath] * where 'app' is first one or two directories in the path * (e.g. /ondemand/, /flash/live/, etc.) * and 'playpath' is a file name (the rest of the path, * may be prefixed with "mp4:") */ static int rtmp_open(URLContext *s, const char *uri, int flags) { RTMPContext *rt; char proto[8], hostname[256], path[1024], *fname; uint8_t buf[2048]; int port; int ret; rt = av_mallocz(sizeof(RTMPContext)); if (!rt) return AVERROR(ENOMEM); s->priv_data = rt; rt->is_input = !(flags & URL_WRONLY); ff_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port, path, sizeof(path), s->filename); if (port < 0) port = RTMP_DEFAULT_PORT; ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL); if (url_open(&rt->stream, buf, URL_RDWR) < 0) { av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot open connection %s\n", buf); goto fail; } rt->state = STATE_START; if (rtmp_handshake(s, rt)) return -1; rt->chunk_size = 128; rt->state = STATE_HANDSHAKED; //extract "app" part from path if (!strncmp(path, "/ondemand/", 10)) { fname = path + 10; memcpy(rt->app, "ondemand", 9); } else { char *p = strchr(path + 1, '/'); if (!p) { fname = path + 1; rt->app[0] = '\0'; } else { char *c = strchr(p + 1, ':'); fname = strchr(p + 1, '/'); if (!fname || c < fname) { fname = p + 1; av_strlcpy(rt->app, path + 1, p - path); } else { fname++; av_strlcpy(rt->app, path + 1, fname - path - 1); } } } if (!strchr(fname, ':') && (!strcmp(fname + strlen(fname) - 4, ".f4v") || !strcmp(fname + strlen(fname) - 4, ".mp4"))) { memcpy(rt->playpath, "mp4:", 5); } else { rt->playpath[0] = 0; } strncat(rt->playpath, fname, sizeof(rt->playpath) - 5); rt->client_report_size = 1048576; rt->bytes_read = 0; rt->last_bytes_read = 0; av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n", proto, path, rt->app, rt->playpath); gen_connect(s, rt, proto, hostname, port); do { ret = get_packet(s, 1); } while (ret == EAGAIN); if (ret < 0) goto fail; if (rt->is_input) { // generate FLV header for demuxer rt->flv_size = 13; rt->flv_data = av_realloc(rt->flv_data, rt->flv_size); rt->flv_off = 0; memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size); } else { rt->flv_size = 0; rt->flv_data = NULL; rt->flv_off = 0; } s->max_packet_size = url_get_max_packet_size(rt->stream); s->is_streamed = 1; return 0; fail: rtmp_close(s); return AVERROR(EIO); } static int rtmp_read(URLContext *s, uint8_t *buf, int size) { RTMPContext *rt = s->priv_data; int orig_size = size; int ret; while (size > 0) { int data_left = rt->flv_size - rt->flv_off; if (data_left >= size) { memcpy(buf, rt->flv_data + rt->flv_off, size); rt->flv_off += size; return orig_size; } if (data_left > 0) { memcpy(buf, rt->flv_data + rt->flv_off, data_left); buf += data_left; size -= data_left; rt->flv_off = rt->flv_size; } if ((ret = get_packet(s, 0)) < 0) return ret; } return orig_size; } static int rtmp_write(URLContext *h, uint8_t *buf, int size) { RTMPContext *rt = h->priv_data; int size_temp = size; int pktsize, pkttype; uint32_t ts; const uint8_t *buf_temp = buf; if (size < 11) { av_log(LOG_CONTEXT, AV_LOG_DEBUG, "FLV packet too small %d\n", size); return 0; } do { if (!rt->flv_off) { //skip flv header if (buf_temp[0] == 'F' && buf_temp[1] == 'L' && buf_temp[2] == 'V') { buf_temp += 9 + 4; size_temp -= 9 + 4; } pkttype = bytestream_get_byte(&buf_temp); pktsize = bytestream_get_be24(&buf_temp); ts = bytestream_get_be24(&buf_temp); ts |= bytestream_get_byte(&buf_temp) << 24; bytestream_get_be24(&buf_temp); size_temp -= 11; rt->flv_size = pktsize; //force 12bytes header if (((pkttype == RTMP_PT_VIDEO || pkttype == RTMP_PT_AUDIO) && ts == 0) || pkttype == RTMP_PT_NOTIFY) { if (pkttype == RTMP_PT_NOTIFY) pktsize += 16; rt->prev_pkt[1][RTMP_SOURCE_CHANNEL].channel_id = 0; } //this can be a big packet, it's better to send it right here ff_rtmp_packet_create(&rt->out_pkt, RTMP_SOURCE_CHANNEL, pkttype, ts, pktsize); rt->out_pkt.extra = rt->main_channel_id; rt->flv_data = rt->out_pkt.data; if (pkttype == RTMP_PT_NOTIFY) ff_amf_write_string(&rt->flv_data, "@setDataFrame"); } if (rt->flv_size - rt->flv_off > size_temp) { bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, size_temp); rt->flv_off += size_temp; } else { bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, rt->flv_size - rt->flv_off); rt->flv_off += rt->flv_size - rt->flv_off; } if (rt->flv_off == rt->flv_size) { bytestream_get_be32(&buf_temp); ff_rtmp_packet_write(rt->stream, &rt->out_pkt, rt->chunk_size, rt->prev_pkt[1]); ff_rtmp_packet_destroy(&rt->out_pkt); rt->flv_size = 0; rt->flv_off = 0; } } while (buf_temp - buf < size_temp); return size; } URLProtocol rtmp_protocol = { "rtmp", rtmp_open, rtmp_read, rtmp_write, NULL, /* seek */ rtmp_close, };
123linslouis-android-video-cutter
jni/libavformat/rtmpproto.c
C
asf20
34,577
/* * various utilities for ffmpeg system * copyright (c) 2000, 2001, 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_OS_SUPPORT_H #define AVFORMAT_OS_SUPPORT_H /** * @file * miscellaneous OS support macros and functions. */ #include "config.h" #if defined(__MINGW32__) && !defined(__MINGW32CE__) # include <fcntl.h> # define lseek(f,p,w) _lseeki64((f), (p), (w)) #endif /* defined(__MINGW32__) && !defined(__MINGW32CE__) */ static inline int is_dos_path(const char *path) { #if HAVE_DOS_PATHS if (path[0] && path[1] == ':') return 1; #endif return 0; } #ifdef __BEOS__ # include <sys/socket.h> # include <netinet/in.h> /* not net_server ? */ # include <BeBuild.h> /* R5 didn't have usleep, fake it. Haiku and Zeta has it now. */ # if B_BEOS_VERSION <= B_BEOS_VERSION_5 # include <OS.h> /* doesn't set errno but that's enough */ # define usleep(t) snooze((bigtime_t)(t)) # endif # ifndef SA_RESTART # warning SA_RESTART not implemented; ffserver might misbehave. # define SA_RESTART 0 # endif #endif #if CONFIG_NETWORK #if !HAVE_SOCKLEN_T typedef int socklen_t; #endif /* most of the time closing a socket is just closing an fd */ #if !HAVE_CLOSESOCKET #define closesocket close #endif #if CONFIG_FFSERVER #if !HAVE_POLL_H typedef unsigned long nfds_t; struct pollfd { int fd; short events; /* events to look for */ short revents; /* events that occurred */ }; /* events & revents */ #define POLLIN 0x0001 /* any readable data available */ #define POLLOUT 0x0002 /* file descriptor is writeable */ #define POLLRDNORM POLLIN #define POLLWRNORM POLLOUT #define POLLRDBAND 0x0008 /* priority readable data */ #define POLLWRBAND 0x0010 /* priority data can be written */ #define POLLPRI 0x0020 /* high priority readable data */ /* revents only */ #define POLLERR 0x0004 /* errors pending */ #define POLLHUP 0x0080 /* disconnected */ #define POLLNVAL 0x1000 /* invalid file descriptor */ int poll(struct pollfd *fds, nfds_t numfds, int timeout); #endif /* HAVE_POLL_H */ #endif /* CONFIG_FFSERVER */ #endif /* CONFIG_NETWORK */ #endif /* AVFORMAT_OS_SUPPORT_H */
123linslouis-android-video-cutter
jni/libavformat/os_support.h
C
asf20
2,918
/* * Matroska constants * Copyright (c) 2003-2004 The ffmpeg Project * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_MATROSKA_H #define AVFORMAT_MATROSKA_H #include "libavcodec/avcodec.h" #include "metadata.h" /* EBML version supported */ #define EBML_VERSION 1 /* top-level master-IDs */ #define EBML_ID_HEADER 0x1A45DFA3 /* IDs in the HEADER master */ #define EBML_ID_EBMLVERSION 0x4286 #define EBML_ID_EBMLREADVERSION 0x42F7 #define EBML_ID_EBMLMAXIDLENGTH 0x42F2 #define EBML_ID_EBMLMAXSIZELENGTH 0x42F3 #define EBML_ID_DOCTYPE 0x4282 #define EBML_ID_DOCTYPEVERSION 0x4287 #define EBML_ID_DOCTYPEREADVERSION 0x4285 /* general EBML types */ #define EBML_ID_VOID 0xEC #define EBML_ID_CRC32 0xBF /* * Matroska element IDs, max. 32 bits */ /* toplevel segment */ #define MATROSKA_ID_SEGMENT 0x18538067 /* Matroska top-level master IDs */ #define MATROSKA_ID_INFO 0x1549A966 #define MATROSKA_ID_TRACKS 0x1654AE6B #define MATROSKA_ID_CUES 0x1C53BB6B #define MATROSKA_ID_TAGS 0x1254C367 #define MATROSKA_ID_SEEKHEAD 0x114D9B74 #define MATROSKA_ID_ATTACHMENTS 0x1941A469 #define MATROSKA_ID_CLUSTER 0x1F43B675 #define MATROSKA_ID_CHAPTERS 0x1043A770 /* IDs in the info master */ #define MATROSKA_ID_TIMECODESCALE 0x2AD7B1 #define MATROSKA_ID_DURATION 0x4489 #define MATROSKA_ID_TITLE 0x7BA9 #define MATROSKA_ID_WRITINGAPP 0x5741 #define MATROSKA_ID_MUXINGAPP 0x4D80 #define MATROSKA_ID_DATEUTC 0x4461 #define MATROSKA_ID_SEGMENTUID 0x73A4 /* ID in the tracks master */ #define MATROSKA_ID_TRACKENTRY 0xAE /* IDs in the trackentry master */ #define MATROSKA_ID_TRACKNUMBER 0xD7 #define MATROSKA_ID_TRACKUID 0x73C5 #define MATROSKA_ID_TRACKTYPE 0x83 #define MATROSKA_ID_TRACKAUDIO 0xE1 #define MATROSKA_ID_TRACKVIDEO 0xE0 #define MATROSKA_ID_CODECID 0x86 #define MATROSKA_ID_CODECPRIVATE 0x63A2 #define MATROSKA_ID_CODECNAME 0x258688 #define MATROSKA_ID_CODECINFOURL 0x3B4040 #define MATROSKA_ID_CODECDOWNLOADURL 0x26B240 #define MATROSKA_ID_CODECDECODEALL 0xAA #define MATROSKA_ID_TRACKNAME 0x536E #define MATROSKA_ID_TRACKLANGUAGE 0x22B59C #define MATROSKA_ID_TRACKFLAGENABLED 0xB9 #define MATROSKA_ID_TRACKFLAGDEFAULT 0x88 #define MATROSKA_ID_TRACKFLAGFORCED 0x55AA #define MATROSKA_ID_TRACKFLAGLACING 0x9C #define MATROSKA_ID_TRACKMINCACHE 0x6DE7 #define MATROSKA_ID_TRACKMAXCACHE 0x6DF8 #define MATROSKA_ID_TRACKDEFAULTDURATION 0x23E383 #define MATROSKA_ID_TRACKCONTENTENCODINGS 0x6D80 #define MATROSKA_ID_TRACKCONTENTENCODING 0x6240 #define MATROSKA_ID_TRACKTIMECODESCALE 0x23314F #define MATROSKA_ID_TRACKMAXBLKADDID 0x55EE /* IDs in the trackvideo master */ #define MATROSKA_ID_VIDEOFRAMERATE 0x2383E3 #define MATROSKA_ID_VIDEODISPLAYWIDTH 0x54B0 #define MATROSKA_ID_VIDEODISPLAYHEIGHT 0x54BA #define MATROSKA_ID_VIDEOPIXELWIDTH 0xB0 #define MATROSKA_ID_VIDEOPIXELHEIGHT 0xBA #define MATROSKA_ID_VIDEOPIXELCROPB 0x54AA #define MATROSKA_ID_VIDEOPIXELCROPT 0x54BB #define MATROSKA_ID_VIDEOPIXELCROPL 0x54CC #define MATROSKA_ID_VIDEOPIXELCROPR 0x54DD #define MATROSKA_ID_VIDEODISPLAYUNIT 0x54B2 #define MATROSKA_ID_VIDEOFLAGINTERLACED 0x9A #define MATROSKA_ID_VIDEOSTEREOMODE 0x53B9 #define MATROSKA_ID_VIDEOASPECTRATIO 0x54B3 #define MATROSKA_ID_VIDEOCOLORSPACE 0x2EB524 /* IDs in the trackaudio master */ #define MATROSKA_ID_AUDIOSAMPLINGFREQ 0xB5 #define MATROSKA_ID_AUDIOOUTSAMPLINGFREQ 0x78B5 #define MATROSKA_ID_AUDIOBITDEPTH 0x6264 #define MATROSKA_ID_AUDIOCHANNELS 0x9F /* IDs in the content encoding master */ #define MATROSKA_ID_ENCODINGORDER 0x5031 #define MATROSKA_ID_ENCODINGSCOPE 0x5032 #define MATROSKA_ID_ENCODINGTYPE 0x5033 #define MATROSKA_ID_ENCODINGCOMPRESSION 0x5034 #define MATROSKA_ID_ENCODINGCOMPALGO 0x4254 #define MATROSKA_ID_ENCODINGCOMPSETTINGS 0x4255 /* ID in the cues master */ #define MATROSKA_ID_POINTENTRY 0xBB /* IDs in the pointentry master */ #define MATROSKA_ID_CUETIME 0xB3 #define MATROSKA_ID_CUETRACKPOSITION 0xB7 /* IDs in the cuetrackposition master */ #define MATROSKA_ID_CUETRACK 0xF7 #define MATROSKA_ID_CUECLUSTERPOSITION 0xF1 #define MATROSKA_ID_CUEBLOCKNUMBER 0x5378 /* IDs in the tags master */ #define MATROSKA_ID_TAG 0x7373 #define MATROSKA_ID_SIMPLETAG 0x67C8 #define MATROSKA_ID_TAGNAME 0x45A3 #define MATROSKA_ID_TAGSTRING 0x4487 #define MATROSKA_ID_TAGLANG 0x447A #define MATROSKA_ID_TAGDEFAULT 0x44B4 #define MATROSKA_ID_TAGTARGETS 0x63C0 #define MATROSKA_ID_TAGTARGETS_TYPE 0x63CA #define MATROSKA_ID_TAGTARGETS_TYPEVALUE 0x68CA #define MATROSKA_ID_TAGTARGETS_TRACKUID 0x63C5 #define MATROSKA_ID_TAGTARGETS_CHAPTERUID 0x63C4 #define MATROSKA_ID_TAGTARGETS_ATTACHUID 0x63C6 /* IDs in the seekhead master */ #define MATROSKA_ID_SEEKENTRY 0x4DBB /* IDs in the seekpoint master */ #define MATROSKA_ID_SEEKID 0x53AB #define MATROSKA_ID_SEEKPOSITION 0x53AC /* IDs in the cluster master */ #define MATROSKA_ID_CLUSTERTIMECODE 0xE7 #define MATROSKA_ID_CLUSTERPOSITION 0xA7 #define MATROSKA_ID_CLUSTERPREVSIZE 0xAB #define MATROSKA_ID_BLOCKGROUP 0xA0 #define MATROSKA_ID_SIMPLEBLOCK 0xA3 /* IDs in the blockgroup master */ #define MATROSKA_ID_BLOCK 0xA1 #define MATROSKA_ID_BLOCKDURATION 0x9B #define MATROSKA_ID_BLOCKREFERENCE 0xFB /* IDs in the attachments master */ #define MATROSKA_ID_ATTACHEDFILE 0x61A7 #define MATROSKA_ID_FILEDESC 0x467E #define MATROSKA_ID_FILENAME 0x466E #define MATROSKA_ID_FILEMIMETYPE 0x4660 #define MATROSKA_ID_FILEDATA 0x465C #define MATROSKA_ID_FILEUID 0x46AE /* IDs in the chapters master */ #define MATROSKA_ID_EDITIONENTRY 0x45B9 #define MATROSKA_ID_CHAPTERATOM 0xB6 #define MATROSKA_ID_CHAPTERTIMESTART 0x91 #define MATROSKA_ID_CHAPTERTIMEEND 0x92 #define MATROSKA_ID_CHAPTERDISPLAY 0x80 #define MATROSKA_ID_CHAPSTRING 0x85 #define MATROSKA_ID_CHAPLANG 0x437C #define MATROSKA_ID_EDITIONUID 0x45BC #define MATROSKA_ID_EDITIONFLAGHIDDEN 0x45BD #define MATROSKA_ID_EDITIONFLAGDEFAULT 0x45DB #define MATROSKA_ID_EDITIONFLAGORDERED 0x45DD #define MATROSKA_ID_CHAPTERUID 0x73C4 #define MATROSKA_ID_CHAPTERFLAGHIDDEN 0x98 #define MATROSKA_ID_CHAPTERFLAGENABLED 0x4598 #define MATROSKA_ID_CHAPTERPHYSEQUIV 0x63C3 typedef enum { MATROSKA_TRACK_TYPE_NONE = 0x0, MATROSKA_TRACK_TYPE_VIDEO = 0x1, MATROSKA_TRACK_TYPE_AUDIO = 0x2, MATROSKA_TRACK_TYPE_COMPLEX = 0x3, MATROSKA_TRACK_TYPE_LOGO = 0x10, MATROSKA_TRACK_TYPE_SUBTITLE = 0x11, MATROSKA_TRACK_TYPE_CONTROL = 0x20, } MatroskaTrackType; typedef enum { MATROSKA_TRACK_ENCODING_COMP_ZLIB = 0, MATROSKA_TRACK_ENCODING_COMP_BZLIB = 1, MATROSKA_TRACK_ENCODING_COMP_LZO = 2, MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP = 3, } MatroskaTrackEncodingCompAlgo; /* * Matroska Codec IDs, strings */ typedef struct CodecTags{ char str[20]; enum CodecID id; }CodecTags; typedef struct CodecMime{ char str[32]; enum CodecID id; }CodecMime; /* max. depth in the EBML tree structure */ #define EBML_MAX_DEPTH 16 extern const CodecTags ff_mkv_codec_tags[]; extern const CodecMime ff_mkv_mime_tags[]; extern const AVMetadataConv ff_mkv_metadata_conv[]; #endif /* AVFORMAT_MATROSKA_H */
123linslouis-android-video-cutter
jni/libavformat/matroska.h
C
asf20
8,095
/* * RTSP/SDP client * Copyright (c) 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/base64.h" #include "libavutil/avstring.h" #include "libavutil/intreadwrite.h" #include "avformat.h" #include <sys/time.h> #if HAVE_SYS_SELECT_H #include <sys/select.h> #endif #include <strings.h> #include "internal.h" #include "network.h" #include "os_support.h" #include "rtsp.h" #include "rtpdec.h" #include "rdt.h" #include "rtpdec_asf.h" //#define DEBUG //#define DEBUG_RTP_TCP #if LIBAVFORMAT_VERSION_INT < (53 << 16) int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP); #endif /* Timeout values for socket select, in ms, * and read_packet(), in seconds */ #define SELECT_TIMEOUT_MS 100 #define READ_PACKET_TIMEOUT_S 10 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS #define SPACE_CHARS " \t\r\n" /* we use memchr() instead of strchr() here because strchr() will return * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */ #define redir_isspace(c) memchr(SPACE_CHARS, c, 4) static void skip_spaces(const char **pp) { const char *p; p = *pp; while (redir_isspace(*p)) p++; *pp = p; } static void get_word_until_chars(char *buf, int buf_size, const char *sep, const char **pp) { const char *p; char *q; p = *pp; skip_spaces(&p); q = buf; while (!strchr(sep, *p) && *p != '\0') { if ((q - buf) < buf_size - 1) *q++ = *p; p++; } if (buf_size > 0) *q = '\0'; *pp = p; } static void get_word_sep(char *buf, int buf_size, const char *sep, const char **pp) { if (**pp == '/') (*pp)++; get_word_until_chars(buf, buf_size, sep, pp); } static void get_word(char *buf, int buf_size, const char **pp) { get_word_until_chars(buf, buf_size, SPACE_CHARS, pp); } /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */ static int sdp_parse_rtpmap(AVFormatContext *s, AVCodecContext *codec, RTSPStream *rtsp_st, int payload_type, const char *p) { char buf[256]; int i; AVCodec *c; const char *c_name; /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and * see if we can handle this kind of payload. * The space should normally not be there but some Real streams or * particular servers ("RealServer Version 6.1.3.970", see issue 1658) * have a trailing space. */ get_word_sep(buf, sizeof(buf), "/ ", &p); if (payload_type >= RTP_PT_PRIVATE) { RTPDynamicProtocolHandler *handler; for (handler = RTPFirstDynamicPayloadHandler; handler; handler = handler->next) { if (!strcasecmp(buf, handler->enc_name) && codec->codec_type == handler->codec_type) { codec->codec_id = handler->codec_id; rtsp_st->dynamic_handler = handler; if (handler->open) rtsp_st->dynamic_protocol_context = handler->open(); break; } } } else { /* We are in a standard case * (from http://www.iana.org/assignments/rtp-parameters). */ /* search into AVRtpPayloadTypes[] */ codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type); } c = avcodec_find_decoder(codec->codec_id); if (c && c->name) c_name = c->name; else c_name = "(null)"; get_word_sep(buf, sizeof(buf), "/", &p); i = atoi(buf); switch (codec->codec_type) { case AVMEDIA_TYPE_AUDIO: av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name); codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE; codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS; if (i > 0) { codec->sample_rate = i; get_word_sep(buf, sizeof(buf), "/", &p); i = atoi(buf); if (i > 0) codec->channels = i; // TODO: there is a bug here; if it is a mono stream, and // less than 22000Hz, faad upconverts to stereo and twice // the frequency. No problem, but the sample rate is being // set here by the sdp line. Patch on its way. (rdm) } av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n", codec->sample_rate); av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n", codec->channels); break; case AVMEDIA_TYPE_VIDEO: av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name); break; default: break; } return 0; } /* return the length and optionally the data */ static int hex_to_data(uint8_t *data, const char *p) { int c, len, v; len = 0; v = 1; for (;;) { skip_spaces(&p); if (*p == '\0') break; c = toupper((unsigned char) *p++); if (c >= '0' && c <= '9') c = c - '0'; else if (c >= 'A' && c <= 'F') c = c - 'A' + 10; else break; v = (v << 4) | c; if (v & 0x100) { if (data) data[len] = v; len++; v = 1; } } return len; } static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx, char *attr, char *value) { switch (codec->codec_id) { case CODEC_ID_MPEG4: case CODEC_ID_AAC: if (!strcmp(attr, "config")) { /* decode the hexa encoded parameter */ int len = hex_to_data(NULL, value); if (codec->extradata) av_free(codec->extradata); codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE); if (!codec->extradata) return; codec->extradata_size = len; hex_to_data(codec->extradata, value); } break; default: break; } return; } typedef struct { const char *str; uint16_t type; uint32_t offset; } AttrNameMap; /* All known fmtp parameters and the corresponding RTPAttrTypeEnum */ #define ATTR_NAME_TYPE_INT 0 #define ATTR_NAME_TYPE_STR 1 static const AttrNameMap attr_names[]= { { "SizeLength", ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, sizelength) }, { "IndexLength", ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, indexlength) }, { "IndexDeltaLength", ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, indexdeltalength) }, { "profile-level-id", ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, profile_level_id) }, { "StreamType", ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, streamtype) }, { "mode", ATTR_NAME_TYPE_STR, offsetof(RTPPayloadData, mode) }, { NULL, -1, -1 }, }; /* parse the attribute line from the fmtp a line of an sdp response. This * is broken out as a function because it is used in rtp_h264.c, which is * forthcoming. */ int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size) { skip_spaces(p); if (**p) { get_word_sep(attr, attr_size, "=", p); if (**p == '=') (*p)++; get_word_sep(value, value_size, ";", p); if (**p == ';') (*p)++; return 1; } return 0; } /* parse a SDP line and save stream attributes */ static void sdp_parse_fmtp(AVStream *st, const char *p) { char attr[256]; /* Vorbis setup headers can be up to 12KB and are sent base64 * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */ char value[16384]; int i; RTSPStream *rtsp_st = st->priv_data; AVCodecContext *codec = st->codec; RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data; /* loop on each attribute */ while (ff_rtsp_next_attr_and_value(&p, attr, sizeof(attr), value, sizeof(value))) { /* grab the codec extra_data from the config parameter of the fmtp * line */ sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context, attr, value); /* Looking for a known attribute */ for (i = 0; attr_names[i].str; ++i) { if (!strcasecmp(attr, attr_names[i].str)) { if (attr_names[i].type == ATTR_NAME_TYPE_INT) { *(int *)((char *)rtp_payload_data + attr_names[i].offset) = atoi(value); } else if (attr_names[i].type == ATTR_NAME_TYPE_STR) *(char **)((char *)rtp_payload_data + attr_names[i].offset) = av_strdup(value); } } } } /** Parse a string p in the form of Range:npt=xx-xx, and determine the start * and end time. * Used for seeking in the rtp stream. */ static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end) { char buf[256]; skip_spaces(&p); if (!av_stristart(p, "npt=", &p)) return; *start = AV_NOPTS_VALUE; *end = AV_NOPTS_VALUE; get_word_sep(buf, sizeof(buf), "-", &p); *start = parse_date(buf, 1); if (*p == '-') { p++; get_word_sep(buf, sizeof(buf), "-", &p); *end = parse_date(buf, 1); } // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start); // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end); } typedef struct SDPParseState { /* SDP only */ struct in_addr default_ip; int default_ttl; int skip_media; ///< set if an unknown m= line occurs } SDPParseState; static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1, int letter, const char *buf) { RTSPState *rt = s->priv_data; char buf1[64], st_type[64]; const char *p; enum AVMediaType codec_type; int payload_type, i; AVStream *st; RTSPStream *rtsp_st; struct in_addr sdp_ip; int ttl; dprintf(s, "sdp: %c='%s'\n", letter, buf); p = buf; if (s1->skip_media && letter != 'm') return; switch (letter) { case 'c': get_word(buf1, sizeof(buf1), &p); if (strcmp(buf1, "IN") != 0) return; get_word(buf1, sizeof(buf1), &p); if (strcmp(buf1, "IP4") != 0) return; get_word_sep(buf1, sizeof(buf1), "/", &p); if (ff_inet_aton(buf1, &sdp_ip) == 0) return; ttl = 16; if (*p == '/') { p++; get_word_sep(buf1, sizeof(buf1), "/", &p); ttl = atoi(buf1); } if (s->nb_streams == 0) { s1->default_ip = sdp_ip; s1->default_ttl = ttl; } else { st = s->streams[s->nb_streams - 1]; rtsp_st = st->priv_data; rtsp_st->sdp_ip = sdp_ip; rtsp_st->sdp_ttl = ttl; } break; case 's': av_metadata_set2(&s->metadata, "title", p, 0); break; case 'i': if (s->nb_streams == 0) { av_metadata_set2(&s->metadata, "comment", p, 0); break; } break; case 'm': /* new stream */ s1->skip_media = 0; get_word(st_type, sizeof(st_type), &p); if (!strcmp(st_type, "audio")) { codec_type = AVMEDIA_TYPE_AUDIO; } else if (!strcmp(st_type, "video")) { codec_type = AVMEDIA_TYPE_VIDEO; } else if (!strcmp(st_type, "application")) { codec_type = AVMEDIA_TYPE_DATA; } else { s1->skip_media = 1; return; } rtsp_st = av_mallocz(sizeof(RTSPStream)); if (!rtsp_st) return; rtsp_st->stream_index = -1; dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st); rtsp_st->sdp_ip = s1->default_ip; rtsp_st->sdp_ttl = s1->default_ttl; get_word(buf1, sizeof(buf1), &p); /* port */ rtsp_st->sdp_port = atoi(buf1); get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */ /* XXX: handle list of formats */ get_word(buf1, sizeof(buf1), &p); /* format list */ rtsp_st->sdp_payload_type = atoi(buf1); if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) { /* no corresponding stream */ } else { st = av_new_stream(s, 0); if (!st) return; st->priv_data = rtsp_st; rtsp_st->stream_index = st->index; st->codec->codec_type = codec_type; if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) { /* if standard payload type, we can find the codec right now */ ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type); } } /* put a default control url */ av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url)); break; case 'a': if (av_strstart(p, "control:", &p)) { if (s->nb_streams == 0) { if (!strncmp(p, "rtsp://", 7)) av_strlcpy(rt->control_uri, p, sizeof(rt->control_uri)); } else { char proto[32]; /* get the control url */ st = s->streams[s->nb_streams - 1]; rtsp_st = st->priv_data; /* XXX: may need to add full url resolution */ ff_url_split(proto, sizeof(proto), NULL, 0, NULL, 0, NULL, NULL, 0, p); if (proto[0] == '\0') { /* relative control URL */ if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/') av_strlcat(rtsp_st->control_url, "/", sizeof(rtsp_st->control_url)); av_strlcat(rtsp_st->control_url, p, sizeof(rtsp_st->control_url)); } else av_strlcpy(rtsp_st->control_url, p, sizeof(rtsp_st->control_url)); } } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) { /* NOTE: rtpmap is only supported AFTER the 'm=' tag */ get_word(buf1, sizeof(buf1), &p); payload_type = atoi(buf1); st = s->streams[s->nb_streams - 1]; rtsp_st = st->priv_data; sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p); } else if (av_strstart(p, "fmtp:", &p)) { /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */ get_word(buf1, sizeof(buf1), &p); payload_type = atoi(buf1); for (i = 0; i < s->nb_streams; i++) { st = s->streams[i]; rtsp_st = st->priv_data; if (rtsp_st->sdp_payload_type == payload_type) { if (!(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line && rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf))) sdp_parse_fmtp(st, p); } } } else if (av_strstart(p, "framesize:", &p)) { // let dynamic protocol handlers have a stab at the line. get_word(buf1, sizeof(buf1), &p); payload_type = atoi(buf1); for (i = 0; i < s->nb_streams; i++) { st = s->streams[i]; rtsp_st = st->priv_data; if (rtsp_st->sdp_payload_type == payload_type && rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf); } } else if (av_strstart(p, "range:", &p)) { int64_t start, end; // this is so that seeking on a streamed file can work. rtsp_parse_range_npt(p, &start, &end); s->start_time = start; /* AV_NOPTS_VALUE means live broadcast (and can't seek) */ s->duration = (end == AV_NOPTS_VALUE) ? AV_NOPTS_VALUE : end - start; } else if (av_strstart(p, "IsRealDataType:integer;",&p)) { if (atoi(p) == 1) rt->transport = RTSP_TRANSPORT_RDT; } else { if (rt->server_type == RTSP_SERVER_WMS) ff_wms_parse_sdp_a_line(s, p); if (s->nb_streams > 0) { if (rt->server_type == RTSP_SERVER_REAL) ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p); rtsp_st = s->streams[s->nb_streams - 1]->priv_data; if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) rtsp_st->dynamic_handler->parse_sdp_a_line(s, s->nb_streams - 1, rtsp_st->dynamic_protocol_context, buf); } } break; } } static int sdp_parse(AVFormatContext *s, const char *content) { const char *p; int letter; /* Some SDP lines, particularly for Realmedia or ASF RTSP streams, * contain long SDP lines containing complete ASF Headers (several * kB) or arrays of MDPR (RM stream descriptor) headers plus * "rulebooks" describing their properties. Therefore, the SDP line * buffer is large. * * The Vorbis FMTP line can be up to 16KB - see sdp_parse_fmtp. */ char buf[16384], *q; SDPParseState sdp_parse_state, *s1 = &sdp_parse_state; memset(s1, 0, sizeof(SDPParseState)); p = content; for (;;) { skip_spaces(&p); letter = *p; if (letter == '\0') break; p++; if (*p != '=') goto next_line; p++; /* get the content */ q = buf; while (*p != '\n' && *p != '\r' && *p != '\0') { if ((q - buf) < sizeof(buf) - 1) *q++ = *p; p++; } *q = '\0'; sdp_parse_line(s, s1, letter, buf); next_line: while (*p != '\n' && *p != '\0') p++; if (*p == '\n') p++; } return 0; } /* close and free RTSP streams */ void ff_rtsp_close_streams(AVFormatContext *s) { RTSPState *rt = s->priv_data; int i; RTSPStream *rtsp_st; for (i = 0; i < rt->nb_rtsp_streams; i++) { rtsp_st = rt->rtsp_streams[i]; if (rtsp_st) { if (rtsp_st->transport_priv) { if (s->oformat) { AVFormatContext *rtpctx = rtsp_st->transport_priv; av_write_trailer(rtpctx); if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) { uint8_t *ptr; url_close_dyn_buf(rtpctx->pb, &ptr); av_free(ptr); } else { url_fclose(rtpctx->pb); } av_metadata_free(&rtpctx->streams[0]->metadata); av_metadata_free(&rtpctx->metadata); av_free(rtpctx->streams[0]); av_free(rtpctx); } else if (rt->transport == RTSP_TRANSPORT_RDT) ff_rdt_parse_close(rtsp_st->transport_priv); else rtp_parse_close(rtsp_st->transport_priv); } if (rtsp_st->rtp_handle) url_close(rtsp_st->rtp_handle); if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context) rtsp_st->dynamic_handler->close( rtsp_st->dynamic_protocol_context); } } av_free(rt->rtsp_streams); if (rt->asf_ctx) { av_close_input_stream (rt->asf_ctx); rt->asf_ctx = NULL; } } static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st, URLContext *handle) { RTSPState *rt = s->priv_data; AVFormatContext *rtpctx; int ret; AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL); if (!rtp_format) return NULL; /* Allocate an AVFormatContext for each output stream */ rtpctx = avformat_alloc_context(); if (!rtpctx) return NULL; rtpctx->oformat = rtp_format; if (!av_new_stream(rtpctx, 0)) { av_free(rtpctx); return NULL; } /* Copy the max delay setting; the rtp muxer reads this. */ rtpctx->max_delay = s->max_delay; /* Copy other stream parameters. */ rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio; /* Set the synchronized start time. */ rtpctx->start_time_realtime = rt->start_time; /* Remove the local codec, link to the original codec * context instead, to give the rtp muxer access to * codec parameters. */ av_free(rtpctx->streams[0]->codec); rtpctx->streams[0]->codec = st->codec; if (handle) { url_fdopen(&rtpctx->pb, handle); } else url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE); ret = av_write_header(rtpctx); if (ret) { if (handle) { url_fclose(rtpctx->pb); } else { uint8_t *ptr; url_close_dyn_buf(rtpctx->pb, &ptr); av_free(ptr); } av_free(rtpctx->streams[0]); av_free(rtpctx); return NULL; } /* Copy the RTP AVStream timebase back to the original AVStream */ st->time_base = rtpctx->streams[0]->time_base; return rtpctx; } static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st) { RTSPState *rt = s->priv_data; AVStream *st = NULL; /* open the RTP context */ if (rtsp_st->stream_index >= 0) st = s->streams[rtsp_st->stream_index]; if (!st) s->ctx_flags |= AVFMTCTX_NOHEADER; if (s->oformat) { rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle); /* Ownership of rtp_handle is passed to the rtp mux context */ rtsp_st->rtp_handle = NULL; } else if (rt->transport == RTSP_TRANSPORT_RDT) rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index, rtsp_st->dynamic_protocol_context, rtsp_st->dynamic_handler); else rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle, rtsp_st->sdp_payload_type, &rtsp_st->rtp_payload_data); if (!rtsp_st->transport_priv) { return AVERROR(ENOMEM); } else if (rt->transport != RTSP_TRANSPORT_RDT) { if (rtsp_st->dynamic_handler) { rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv, rtsp_st->dynamic_protocol_context, rtsp_st->dynamic_handler); } } return 0; } #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER static int rtsp_probe(AVProbeData *p) { if (av_strstart(p->filename, "rtsp:", NULL)) return AVPROBE_SCORE_MAX; return 0; } static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp) { const char *p; int v; p = *pp; skip_spaces(&p); v = strtol(p, (char **)&p, 10); if (*p == '-') { p++; *min_ptr = v; v = strtol(p, (char **)&p, 10); *max_ptr = v; } else { *min_ptr = v; *max_ptr = v; } *pp = p; } /* XXX: only one transport specification is parsed */ static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p) { char transport_protocol[16]; char profile[16]; char lower_transport[16]; char parameter[16]; RTSPTransportField *th; char buf[256]; reply->nb_transports = 0; for (;;) { skip_spaces(&p); if (*p == '\0') break; th = &reply->transports[reply->nb_transports]; get_word_sep(transport_protocol, sizeof(transport_protocol), "/", &p); if (!strcasecmp (transport_protocol, "rtp")) { get_word_sep(profile, sizeof(profile), "/;,", &p); lower_transport[0] = '\0'; /* rtp/avp/<protocol> */ if (*p == '/') { get_word_sep(lower_transport, sizeof(lower_transport), ";,", &p); } th->transport = RTSP_TRANSPORT_RTP; } else if (!strcasecmp (transport_protocol, "x-pn-tng") || !strcasecmp (transport_protocol, "x-real-rdt")) { /* x-pn-tng/<protocol> */ get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p); profile[0] = '\0'; th->transport = RTSP_TRANSPORT_RDT; } if (!strcasecmp(lower_transport, "TCP")) th->lower_transport = RTSP_LOWER_TRANSPORT_TCP; else th->lower_transport = RTSP_LOWER_TRANSPORT_UDP; if (*p == ';') p++; /* get each parameter */ while (*p != '\0' && *p != ',') { get_word_sep(parameter, sizeof(parameter), "=;,", &p); if (!strcmp(parameter, "port")) { if (*p == '=') { p++; rtsp_parse_range(&th->port_min, &th->port_max, &p); } } else if (!strcmp(parameter, "client_port")) { if (*p == '=') { p++; rtsp_parse_range(&th->client_port_min, &th->client_port_max, &p); } } else if (!strcmp(parameter, "server_port")) { if (*p == '=') { p++; rtsp_parse_range(&th->server_port_min, &th->server_port_max, &p); } } else if (!strcmp(parameter, "interleaved")) { if (*p == '=') { p++; rtsp_parse_range(&th->interleaved_min, &th->interleaved_max, &p); } } else if (!strcmp(parameter, "multicast")) { if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP) th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST; } else if (!strcmp(parameter, "ttl")) { if (*p == '=') { p++; th->ttl = strtol(p, (char **)&p, 10); } } else if (!strcmp(parameter, "destination")) { struct in_addr ipaddr; if (*p == '=') { p++; get_word_sep(buf, sizeof(buf), ";,", &p); if (ff_inet_aton(buf, &ipaddr)) th->destination = ntohl(ipaddr.s_addr); } } while (*p != ';' && *p != '\0' && *p != ',') p++; if (*p == ';') p++; } if (*p == ',') p++; reply->nb_transports++; } } void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf, HTTPAuthState *auth_state) { const char *p; /* NOTE: we do case independent match for broken servers */ p = buf; if (av_stristart(p, "Session:", &p)) { int t; get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p); if (av_stristart(p, ";timeout=", &p) && (t = strtol(p, NULL, 10)) > 0) { reply->timeout = t; } } else if (av_stristart(p, "Content-Length:", &p)) { reply->content_length = strtol(p, NULL, 10); } else if (av_stristart(p, "Transport:", &p)) { rtsp_parse_transport(reply, p); } else if (av_stristart(p, "CSeq:", &p)) { reply->seq = strtol(p, NULL, 10); } else if (av_stristart(p, "Range:", &p)) { rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end); } else if (av_stristart(p, "RealChallenge1:", &p)) { skip_spaces(&p); av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge)); } else if (av_stristart(p, "Server:", &p)) { skip_spaces(&p); av_strlcpy(reply->server, p, sizeof(reply->server)); } else if (av_stristart(p, "Notice:", &p) || av_stristart(p, "X-Notice:", &p)) { reply->notice = strtol(p, NULL, 10); } else if (av_stristart(p, "Location:", &p)) { skip_spaces(&p); av_strlcpy(reply->location, p , sizeof(reply->location)); } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) { skip_spaces(&p); ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p); } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) { skip_spaces(&p); ff_http_auth_handle_header(auth_state, "Authentication-Info", p); } } /* skip a RTP/TCP interleaved packet */ void ff_rtsp_skip_packet(AVFormatContext *s) { RTSPState *rt = s->priv_data; int ret, len, len1; uint8_t buf[1024]; ret = url_read_complete(rt->rtsp_hd, buf, 3); if (ret != 3) return; len = AV_RB16(buf + 1); dprintf(s, "skipping RTP packet len=%d\n", len); /* skip payload */ while (len > 0) { len1 = len; if (len1 > sizeof(buf)) len1 = sizeof(buf); ret = url_read_complete(rt->rtsp_hd, buf, len1); if (ret != len1) return; len -= len1; } } int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply, unsigned char **content_ptr, int return_on_interleaved_data) { RTSPState *rt = s->priv_data; char buf[4096], buf1[1024], *q; unsigned char ch; const char *p; int ret, content_length, line_count = 0; unsigned char *content = NULL; memset(reply, 0, sizeof(*reply)); /* parse reply (XXX: use buffers) */ rt->last_reply[0] = '\0'; for (;;) { q = buf; for (;;) { ret = url_read_complete(rt->rtsp_hd, &ch, 1); #ifdef DEBUG_RTP_TCP dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch); #endif if (ret != 1) return -1; if (ch == '\n') break; if (ch == '$') { /* XXX: only parse it if first char on line ? */ if (return_on_interleaved_data) { return 1; } else ff_rtsp_skip_packet(s); } else if (ch != '\r') { if ((q - buf) < sizeof(buf) - 1) *q++ = ch; } } *q = '\0'; dprintf(s, "line='%s'\n", buf); /* test if last line */ if (buf[0] == '\0') break; p = buf; if (line_count == 0) { /* get reply code */ get_word(buf1, sizeof(buf1), &p); get_word(buf1, sizeof(buf1), &p); reply->status_code = atoi(buf1); } else { ff_rtsp_parse_line(reply, p, &rt->auth_state); av_strlcat(rt->last_reply, p, sizeof(rt->last_reply)); av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply)); } line_count++; } if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0') av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id)); content_length = reply->content_length; if (content_length > 0) { /* leave some room for a trailing '\0' (useful for simple parsing) */ content = av_malloc(content_length + 1); (void)url_read_complete(rt->rtsp_hd, content, content_length); content[content_length] = '\0'; } if (content_ptr) *content_ptr = content; else av_free(content); if (rt->seq != reply->seq) { av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n", rt->seq, reply->seq); } /* EOS */ if (reply->notice == 2101 /* End-of-Stream Reached */ || reply->notice == 2104 /* Start-of-Stream Reached */ || reply->notice == 2306 /* Continuous Feed Terminated */) { rt->state = RTSP_STATE_IDLE; } else if (reply->notice >= 4400 && reply->notice < 5500) { return AVERROR(EIO); /* data or server error */ } else if (reply->notice == 2401 /* Ticket Expired */ || (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ ) return AVERROR(EPERM); return 0; } void ff_rtsp_send_cmd_with_content_async(AVFormatContext *s, const char *method, const char *url, const char *headers, const unsigned char *send_content, int send_content_length) { RTSPState *rt = s->priv_data; char buf[4096]; rt->seq++; snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url); if (headers) av_strlcat(buf, headers, sizeof(buf)); av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq); if (rt->session_id[0] != '\0' && (!headers || !strstr(headers, "\nIf-Match:"))) { av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id); } if (rt->auth[0]) { char *str = ff_http_auth_create_response(&rt->auth_state, rt->auth, url, method); if (str) av_strlcat(buf, str, sizeof(buf)); av_free(str); } if (send_content_length > 0 && send_content) av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length); av_strlcat(buf, "\r\n", sizeof(buf)); dprintf(s, "Sending:\n%s--\n", buf); url_write(rt->rtsp_hd, buf, strlen(buf)); if (send_content_length > 0 && send_content) url_write(rt->rtsp_hd, send_content, send_content_length); rt->last_cmd_time = av_gettime(); } void ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method, const char *url, const char *headers) { ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0); } void ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url, const char *headers, RTSPMessageHeader *reply, unsigned char **content_ptr) { ff_rtsp_send_cmd_with_content(s, method, url, headers, reply, content_ptr, NULL, 0); } void ff_rtsp_send_cmd_with_content(AVFormatContext *s, const char *method, const char *url, const char *header, RTSPMessageHeader *reply, unsigned char **content_ptr, const unsigned char *send_content, int send_content_length) { RTSPState *rt = s->priv_data; HTTPAuthType cur_auth_type; retry: cur_auth_type = rt->auth_state.auth_type; ff_rtsp_send_cmd_with_content_async(s, method, url, header, send_content, send_content_length); ff_rtsp_read_reply(s, reply, content_ptr, 0); if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE && rt->auth_state.auth_type != HTTP_AUTH_NONE) goto retry; } /** * @return 0 on success, <0 on error, 1 if protocol is unavailable. */ static int make_setup_request(AVFormatContext *s, const char *host, int port, int lower_transport, const char *real_challenge) { RTSPState *rt = s->priv_data; int rtx, j, i, err, interleave = 0; RTSPStream *rtsp_st; RTSPMessageHeader reply1, *reply = &reply1; char cmd[2048]; const char *trans_pref; if (rt->transport == RTSP_TRANSPORT_RDT) trans_pref = "x-pn-tng"; else trans_pref = "RTP/AVP"; /* default timeout: 1 minute */ rt->timeout = 60; /* for each stream, make the setup request */ /* XXX: we assume the same server is used for the control of each * RTSP stream */ for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) { char transport[2048]; /** * WMS serves all UDP data over a single connection, the RTX, which * isn't necessarily the first in the SDP but has to be the first * to be set up, else the second/third SETUP will fail with a 461. */ if (lower_transport == RTSP_LOWER_TRANSPORT_UDP && rt->server_type == RTSP_SERVER_WMS) { if (i == 0) { /* rtx first */ for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) { int len = strlen(rt->rtsp_streams[rtx]->control_url); if (len >= 4 && !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4, "/rtx")) break; } if (rtx == rt->nb_rtsp_streams) return -1; /* no RTX found */ rtsp_st = rt->rtsp_streams[rtx]; } else rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1]; } else rtsp_st = rt->rtsp_streams[i]; /* RTP/UDP */ if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) { char buf[256]; if (rt->server_type == RTSP_SERVER_WMS && i > 1) { port = reply->transports[0].client_port_min; goto have_port; } /* first try in specified port range */ if (RTSP_RTP_PORT_MIN != 0) { while (j <= RTSP_RTP_PORT_MAX) { ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1, "?localport=%d", j); /* we will use two ports per rtp stream (rtp and rtcp) */ j += 2; if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0) goto rtp_opened; } } #if 0 /* then try on any port */ if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) { err = AVERROR_INVALIDDATA; goto fail; } #endif rtp_opened: port = rtp_get_local_port(rtsp_st->rtp_handle); have_port: snprintf(transport, sizeof(transport) - 1, "%s/UDP;", trans_pref); if (rt->server_type != RTSP_SERVER_REAL) av_strlcat(transport, "unicast;", sizeof(transport)); av_strlcatf(transport, sizeof(transport), "client_port=%d", port); if (rt->transport == RTSP_TRANSPORT_RTP && !(rt->server_type == RTSP_SERVER_WMS && i > 0)) av_strlcatf(transport, sizeof(transport), "-%d", port + 1); } /* RTP/TCP */ else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) { /** For WMS streams, the application streams are only used for * UDP. When trying to set it up for TCP streams, the server * will return an error. Therefore, we skip those streams. */ if (rt->server_type == RTSP_SERVER_WMS && s->streams[rtsp_st->stream_index]->codec->codec_type == AVMEDIA_TYPE_DATA) continue; snprintf(transport, sizeof(transport) - 1, "%s/TCP;", trans_pref); if (rt->server_type == RTSP_SERVER_WMS) av_strlcat(transport, "unicast;", sizeof(transport)); av_strlcatf(transport, sizeof(transport), "interleaved=%d-%d", interleave, interleave + 1); interleave += 2; } else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) { snprintf(transport, sizeof(transport) - 1, "%s/UDP;multicast", trans_pref); } if (s->oformat) { av_strlcat(transport, ";mode=receive", sizeof(transport)); } else if (rt->server_type == RTSP_SERVER_REAL || rt->server_type == RTSP_SERVER_WMS) av_strlcat(transport, ";mode=play", sizeof(transport)); snprintf(cmd, sizeof(cmd), "Transport: %s\r\n", transport); if (i == 0 && rt->server_type == RTSP_SERVER_REAL) { char real_res[41], real_csum[9]; ff_rdt_calc_response_and_checksum(real_res, real_csum, real_challenge); av_strlcatf(cmd, sizeof(cmd), "If-Match: %s\r\n" "RealChallenge2: %s, sd=%s\r\n", rt->session_id, real_res, real_csum); } ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL); if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) { err = 1; goto fail; } else if (reply->status_code != RTSP_STATUS_OK || reply->nb_transports != 1) { err = AVERROR_INVALIDDATA; goto fail; } /* XXX: same protocol for all streams is required */ if (i > 0) { if (reply->transports[0].lower_transport != rt->lower_transport || reply->transports[0].transport != rt->transport) { err = AVERROR_INVALIDDATA; goto fail; } } else { rt->lower_transport = reply->transports[0].lower_transport; rt->transport = reply->transports[0].transport; } /* close RTP connection if not choosen */ if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP && (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) { url_close(rtsp_st->rtp_handle); rtsp_st->rtp_handle = NULL; } switch(reply->transports[0].lower_transport) { case RTSP_LOWER_TRANSPORT_TCP: rtsp_st->interleaved_min = reply->transports[0].interleaved_min; rtsp_st->interleaved_max = reply->transports[0].interleaved_max; break; case RTSP_LOWER_TRANSPORT_UDP: { char url[1024]; /* XXX: also use address if specified */ ff_url_join(url, sizeof(url), "rtp", NULL, host, reply->transports[0].server_port_min, NULL); if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) { err = AVERROR_INVALIDDATA; goto fail; } /* Try to initialize the connection state in a * potential NAT router by sending dummy packets. * RTP/RTCP dummy packets are used for RDT, too. */ if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat) rtp_send_punch_packets(rtsp_st->rtp_handle); break; } case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: { char url[1024]; struct in_addr in; int port, ttl; if (reply->transports[0].destination) { in.s_addr = htonl(reply->transports[0].destination); port = reply->transports[0].port_min; ttl = reply->transports[0].ttl; } else { in = rtsp_st->sdp_ip; port = rtsp_st->sdp_port; ttl = rtsp_st->sdp_ttl; } ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in), port, "?ttl=%d", ttl); if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) { err = AVERROR_INVALIDDATA; goto fail; } break; } } if ((err = rtsp_open_transport_ctx(s, rtsp_st))) goto fail; } if (reply->timeout > 0) rt->timeout = reply->timeout; if (rt->server_type == RTSP_SERVER_REAL) rt->need_subscription = 1; return 0; fail: for (i = 0; i < rt->nb_rtsp_streams; i++) { if (rt->rtsp_streams[i]->rtp_handle) { url_close(rt->rtsp_streams[i]->rtp_handle); rt->rtsp_streams[i]->rtp_handle = NULL; } } return err; } static int rtsp_read_play(AVFormatContext *s) { RTSPState *rt = s->priv_data; RTSPMessageHeader reply1, *reply = &reply1; int i; char cmd[1024]; av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state); if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) { if (rt->state == RTSP_STATE_PAUSED) { cmd[0] = 0; } else { snprintf(cmd, sizeof(cmd), "Range: npt=%0.3f-\r\n", (double)rt->seek_timestamp / AV_TIME_BASE); } ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) { return -1; } if (reply->range_start != AV_NOPTS_VALUE && rt->transport == RTSP_TRANSPORT_RTP) { for (i = 0; i < rt->nb_rtsp_streams; i++) { RTSPStream *rtsp_st = rt->rtsp_streams[i]; RTPDemuxContext *rtpctx = rtsp_st->transport_priv; AVStream *st = NULL; if (!rtpctx) continue; if (rtsp_st->stream_index >= 0) st = s->streams[rtsp_st->stream_index]; rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE; rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE; if (st) rtpctx->range_start_offset = av_rescale_q(reply->range_start, AV_TIME_BASE_Q, st->time_base); } } } rt->state = RTSP_STATE_STREAMING; return 0; } static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply) { RTSPState *rt = s->priv_data; char cmd[1024]; unsigned char *content = NULL; int ret; /* describe the stream */ snprintf(cmd, sizeof(cmd), "Accept: application/sdp\r\n"); if (rt->server_type == RTSP_SERVER_REAL) { /** * The Require: attribute is needed for proper streaming from * Realmedia servers. */ av_strlcat(cmd, "Require: com.real.retain-entity-for-setup\r\n", sizeof(cmd)); } ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content); if (!content) return AVERROR_INVALIDDATA; if (reply->status_code != RTSP_STATUS_OK) { av_freep(&content); return AVERROR_INVALIDDATA; } /* now we got the SDP description, we parse it */ ret = sdp_parse(s, (const char *)content); av_freep(&content); if (ret < 0) return AVERROR_INVALIDDATA; return 0; } static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr) { RTSPState *rt = s->priv_data; RTSPMessageHeader reply1, *reply = &reply1; int i; char *sdp; AVFormatContext sdp_ctx, *ctx_array[1]; rt->start_time = av_gettime(); /* Announce the stream */ sdp = av_mallocz(8192); if (sdp == NULL) return AVERROR(ENOMEM); /* We create the SDP based on the RTSP AVFormatContext where we * aren't allowed to change the filename field. (We create the SDP * based on the RTSP context since the contexts for the RTP streams * don't exist yet.) In order to specify a custom URL with the actual * peer IP instead of the originally specified hostname, we create * a temporary copy of the AVFormatContext, where the custom URL is set. * * FIXME: Create the SDP without copying the AVFormatContext. * This either requires setting up the RTP stream AVFormatContexts * already here (complicating things immensely) or getting a more * flexible SDP creation interface. */ sdp_ctx = *s; ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename), "rtsp", NULL, addr, -1, NULL); ctx_array[0] = &sdp_ctx; if (avf_sdp_create(ctx_array, 1, sdp, 8192)) { av_free(sdp); return AVERROR_INVALIDDATA; } av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp); ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri, "Content-Type: application/sdp\r\n", reply, NULL, sdp, strlen(sdp)); av_free(sdp); if (reply->status_code != RTSP_STATUS_OK) return AVERROR_INVALIDDATA; /* Set up the RTSPStreams for each AVStream */ for (i = 0; i < s->nb_streams; i++) { RTSPStream *rtsp_st; AVStream *st = s->streams[i]; rtsp_st = av_mallocz(sizeof(RTSPStream)); if (!rtsp_st) return AVERROR(ENOMEM); dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st); st->priv_data = rtsp_st; rtsp_st->stream_index = i; av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url)); /* Note, this must match the relative uri set in the sdp content */ av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url), "/streamid=%d", i); } return 0; } int ff_rtsp_connect(AVFormatContext *s) { RTSPState *rt = s->priv_data; char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128]; char *option_list, *option, *filename; URLContext *rtsp_hd; int port, err, tcp_fd; RTSPMessageHeader reply1 = {}, *reply = &reply1; int lower_transport_mask = 0; char real_challenge[64]; struct sockaddr_storage peer; socklen_t peer_len = sizeof(peer); if (!ff_network_init()) return AVERROR(EIO); redirect: /* extract hostname and port */ ff_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port, path, sizeof(path), s->filename); if (*auth) { av_strlcpy(rt->auth, auth, sizeof(rt->auth)); } if (port < 0) port = RTSP_DEFAULT_PORT; /* search for options */ option_list = strrchr(path, '?'); if (option_list) { /* Strip out the RTSP specific options, write out the rest of * the options back into the same string. */ filename = option_list; while (option_list) { /* move the option pointer */ option = ++option_list; option_list = strchr(option_list, '&'); if (option_list) *option_list = 0; /* handle the options */ if (!strcmp(option, "udp")) { lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP); } else if (!strcmp(option, "multicast")) { lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST); } else if (!strcmp(option, "tcp")) { lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP); } else { /* Write options back into the buffer, using memmove instead * of strcpy since the strings may overlap. */ int len = strlen(option); memmove(++filename, option, len); filename += len; if (option_list) *filename = '&'; } } *filename = 0; } if (!lower_transport_mask) lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1; if (s->oformat) { /* Only UDP or TCP - UDP multicast isn't supported. */ lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) | (1 << RTSP_LOWER_TRANSPORT_TCP); if (!lower_transport_mask) { av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, " "only UDP and TCP are supported for output.\n"); err = AVERROR(EINVAL); goto fail; } } /* Construct the URI used in request; this is similar to s->filename, * but with authentication credentials removed and RTSP specific options * stripped out. */ ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL, host, port, "%s", path); /* open the tcp connexion */ ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL); if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) { err = AVERROR(EIO); goto fail; } rt->rtsp_hd = rtsp_hd; rt->seq = 0; tcp_fd = url_get_file_handle(rtsp_hd); if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) { getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host), NULL, 0, NI_NUMERICHOST); } /* request options supported by the server; this also detects server * type */ for (rt->server_type = RTSP_SERVER_RTP;;) { cmd[0] = 0; if (rt->server_type == RTSP_SERVER_REAL) av_strlcat(cmd, /** * The following entries are required for proper * streaming from a Realmedia server. They are * interdependent in some way although we currently * don't quite understand how. Values were copied * from mplayer SVN r23589. * @param CompanyID is a 16-byte ID in base64 * @param ClientChallenge is a 16-byte ID in hex */ "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n" "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n" "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n" "GUID: 00000000-0000-0000-0000-000000000000\r\n", sizeof(cmd)); ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) { err = AVERROR_INVALIDDATA; goto fail; } /* detect server type if not standard-compliant RTP */ if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) { rt->server_type = RTSP_SERVER_REAL; continue; } else if (!strncasecmp(reply->server, "WMServer/", 9)) { rt->server_type = RTSP_SERVER_WMS; } else if (rt->server_type == RTSP_SERVER_REAL) strcpy(real_challenge, reply->real_challenge); break; } if (s->iformat) err = rtsp_setup_input_streams(s, reply); else err = rtsp_setup_output_streams(s, host); if (err) goto fail; do { int lower_transport = ff_log2_tab[lower_transport_mask & ~(lower_transport_mask - 1)]; err = make_setup_request(s, host, port, lower_transport, rt->server_type == RTSP_SERVER_REAL ? real_challenge : NULL); if (err < 0) goto fail; lower_transport_mask &= ~(1 << lower_transport); if (lower_transport_mask == 0 && err == 1) { err = FF_NETERROR(EPROTONOSUPPORT); goto fail; } } while (err); rt->state = RTSP_STATE_IDLE; rt->seek_timestamp = 0; /* default is to start stream at position zero */ return 0; fail: ff_rtsp_close_streams(s); url_close(rt->rtsp_hd); if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) { av_strlcpy(s->filename, reply->location, sizeof(s->filename)); av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n", reply->status_code, s->filename); goto redirect; } ff_network_close(); return err; } #endif #if CONFIG_RTSP_DEMUXER static int rtsp_read_header(AVFormatContext *s, AVFormatParameters *ap) { RTSPState *rt = s->priv_data; int ret; ret = ff_rtsp_connect(s); if (ret) return ret; if (ap->initial_pause) { /* do not start immediately */ } else { if (rtsp_read_play(s) < 0) { ff_rtsp_close_streams(s); url_close(rt->rtsp_hd); return AVERROR_INVALIDDATA; } } return 0; } static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st, uint8_t *buf, int buf_size) { RTSPState *rt = s->priv_data; RTSPStream *rtsp_st; fd_set rfds; int fd, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0; struct timeval tv; for (;;) { if (url_interrupt_cb()) return AVERROR(EINTR); FD_ZERO(&rfds); if (rt->rtsp_hd) { tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd); FD_SET(tcp_fd, &rfds); } else { fd_max = 0; tcp_fd = -1; } for (i = 0; i < rt->nb_rtsp_streams; i++) { rtsp_st = rt->rtsp_streams[i]; if (rtsp_st->rtp_handle) { /* currently, we cannot probe RTCP handle because of * blocking restrictions */ fd = url_get_file_handle(rtsp_st->rtp_handle); if (fd > fd_max) fd_max = fd; FD_SET(fd, &rfds); } } tv.tv_sec = 0; tv.tv_usec = SELECT_TIMEOUT_MS * 1000; n = select(fd_max + 1, &rfds, NULL, NULL, &tv); if (n > 0) { timeout_cnt = 0; for (i = 0; i < rt->nb_rtsp_streams; i++) { rtsp_st = rt->rtsp_streams[i]; if (rtsp_st->rtp_handle) { fd = url_get_file_handle(rtsp_st->rtp_handle); if (FD_ISSET(fd, &rfds)) { ret = url_read(rtsp_st->rtp_handle, buf, buf_size); if (ret > 0) { *prtsp_st = rtsp_st; return ret; } } } } #if CONFIG_RTSP_DEMUXER if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) { RTSPMessageHeader reply; ret = ff_rtsp_read_reply(s, &reply, NULL, 0); if (ret < 0) return ret; /* XXX: parse message */ if (rt->state != RTSP_STATE_STREAMING) return 0; } #endif } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) { return FF_NETERROR(ETIMEDOUT); } else if (n < 0 && errno != EINTR) return AVERROR(errno); } } static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st, uint8_t *buf, int buf_size) { RTSPState *rt = s->priv_data; int id, len, i, ret; RTSPStream *rtsp_st; #ifdef DEBUG_RTP_TCP dprintf(s, "tcp_read_packet:\n"); #endif redo: for (;;) { RTSPMessageHeader reply; ret = ff_rtsp_read_reply(s, &reply, NULL, 1); if (ret == -1) return -1; if (ret == 1) /* received '$' */ break; /* XXX: parse message */ if (rt->state != RTSP_STATE_STREAMING) return 0; } ret = url_read_complete(rt->rtsp_hd, buf, 3); if (ret != 3) return -1; id = buf[0]; len = AV_RB16(buf + 1); #ifdef DEBUG_RTP_TCP dprintf(s, "id=%d len=%d\n", id, len); #endif if (len > buf_size || len < 12) goto redo; /* get the data */ ret = url_read_complete(rt->rtsp_hd, buf, len); if (ret != len) return -1; if (rt->transport == RTSP_TRANSPORT_RDT && ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0) return -1; /* find the matching stream */ for (i = 0; i < rt->nb_rtsp_streams; i++) { rtsp_st = rt->rtsp_streams[i]; if (id >= rtsp_st->interleaved_min && id <= rtsp_st->interleaved_max) goto found; } goto redo; found: *prtsp_st = rtsp_st; return len; } static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt) { RTSPState *rt = s->priv_data; int ret, len; uint8_t buf[10 * RTP_MAX_PACKET_LENGTH]; RTSPStream *rtsp_st; /* get next frames from the same RTP packet */ if (rt->cur_transport_priv) { if (rt->transport == RTSP_TRANSPORT_RDT) { ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0); } else ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0); if (ret == 0) { rt->cur_transport_priv = NULL; return 0; } else if (ret == 1) { return 0; } else rt->cur_transport_priv = NULL; } /* read next RTP packet */ redo: switch(rt->lower_transport) { default: #if CONFIG_RTSP_DEMUXER case RTSP_LOWER_TRANSPORT_TCP: len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf)); break; #endif case RTSP_LOWER_TRANSPORT_UDP: case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf)); if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP) rtp_check_and_send_back_rr(rtsp_st->transport_priv, len); break; } if (len < 0) return len; if (len == 0) return AVERROR_EOF; if (rt->transport == RTSP_TRANSPORT_RDT) { ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len); } else { ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len); if (ret < 0) { /* Either bad packet, or a RTCP packet. Check if the * first_rtcp_ntp_time field was initialized. */ RTPDemuxContext *rtpctx = rtsp_st->transport_priv; if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) { /* first_rtcp_ntp_time has been initialized for this stream, * copy the same value to all other uninitialized streams, * in order to map their timestamp origin to the same ntp time * as this one. */ int i; for (i = 0; i < rt->nb_rtsp_streams; i++) { RTPDemuxContext *rtpctx2 = rtsp_st->transport_priv; if (rtpctx2 && rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time; } } } } if (ret < 0) goto redo; if (ret == 1) /* more packets may follow, so we save the RTP context */ rt->cur_transport_priv = rtsp_st->transport_priv; return ret; } static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt) { RTSPState *rt = s->priv_data; int ret; RTSPMessageHeader reply1, *reply = &reply1; char cmd[1024]; if (rt->server_type == RTSP_SERVER_REAL) { int i; enum AVDiscard cache[MAX_STREAMS]; for (i = 0; i < s->nb_streams; i++) cache[i] = s->streams[i]->discard; if (!rt->need_subscription) { if (memcmp (cache, rt->real_setup_cache, sizeof(enum AVDiscard) * s->nb_streams)) { snprintf(cmd, sizeof(cmd), "Unsubscribe: %s\r\n", rt->last_subscription); ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri, cmd, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) return AVERROR_INVALIDDATA; rt->need_subscription = 1; } } if (rt->need_subscription) { int r, rule_nr, first = 1; memcpy(rt->real_setup_cache, cache, sizeof(enum AVDiscard) * s->nb_streams); rt->last_subscription[0] = 0; snprintf(cmd, sizeof(cmd), "Subscribe: "); for (i = 0; i < rt->nb_rtsp_streams; i++) { rule_nr = 0; for (r = 0; r < s->nb_streams; r++) { if (s->streams[r]->priv_data == rt->rtsp_streams[i]) { if (s->streams[r]->discard != AVDISCARD_ALL) { if (!first) av_strlcat(rt->last_subscription, ",", sizeof(rt->last_subscription)); ff_rdt_subscribe_rule( rt->last_subscription, sizeof(rt->last_subscription), i, rule_nr); first = 0; } rule_nr++; } } } av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription); ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri, cmd, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) return AVERROR_INVALIDDATA; rt->need_subscription = 0; if (rt->state == RTSP_STATE_STREAMING) rtsp_read_play (s); } } ret = rtsp_fetch_packet(s, pkt); if (ret < 0) return ret; /* send dummy request to keep TCP connection alive */ if ((rt->server_type == RTSP_SERVER_WMS || rt->server_type == RTSP_SERVER_REAL) && (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) { if (rt->server_type == RTSP_SERVER_WMS) { ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL); } else { ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL); } } return 0; } /* pause the stream */ static int rtsp_read_pause(AVFormatContext *s) { RTSPState *rt = s->priv_data; RTSPMessageHeader reply1, *reply = &reply1; if (rt->state != RTSP_STATE_STREAMING) return 0; else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) { ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) { return -1; } } rt->state = RTSP_STATE_PAUSED; return 0; } static int rtsp_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { RTSPState *rt = s->priv_data; rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q); switch(rt->state) { default: case RTSP_STATE_IDLE: break; case RTSP_STATE_STREAMING: if (rtsp_read_pause(s) != 0) return -1; rt->state = RTSP_STATE_SEEKING; if (rtsp_read_play(s) != 0) return -1; break; case RTSP_STATE_PAUSED: rt->state = RTSP_STATE_IDLE; break; } return 0; } static int rtsp_read_close(AVFormatContext *s) { RTSPState *rt = s->priv_data; #if 0 /* NOTE: it is valid to flush the buffer here */ if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) { url_fclose(&rt->rtsp_gb); } #endif ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL); ff_rtsp_close_streams(s); url_close(rt->rtsp_hd); ff_network_close(); return 0; } AVInputFormat rtsp_demuxer = { "rtsp", NULL_IF_CONFIG_SMALL("RTSP input format"), sizeof(RTSPState), rtsp_probe, rtsp_read_header, rtsp_read_packet, rtsp_read_close, rtsp_read_seek, .flags = AVFMT_NOFILE, .read_play = rtsp_read_play, .read_pause = rtsp_read_pause, }; #endif static int sdp_probe(AVProbeData *p1) { const char *p = p1->buf, *p_end = p1->buf + p1->buf_size; /* we look for a line beginning "c=IN IP4" */ while (p < p_end && *p != '\0') { if (p + sizeof("c=IN IP4") - 1 < p_end && av_strstart(p, "c=IN IP4", NULL)) return AVPROBE_SCORE_MAX / 2; while (p < p_end - 1 && *p != '\n') p++; if (++p >= p_end) break; if (*p == '\r') p++; } return 0; } #define SDP_MAX_SIZE 8192 static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap) { RTSPState *rt = s->priv_data; RTSPStream *rtsp_st; int size, i, err; char *content; char url[1024]; if (!ff_network_init()) return AVERROR(EIO); /* read the whole sdp file */ /* XXX: better loading */ content = av_malloc(SDP_MAX_SIZE); size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1); if (size <= 0) { av_free(content); return AVERROR_INVALIDDATA; } content[size] ='\0'; sdp_parse(s, content); av_free(content); /* open each RTP stream */ for (i = 0; i < rt->nb_rtsp_streams; i++) { rtsp_st = rt->rtsp_streams[i]; ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port, "?localport=%d&ttl=%d", rtsp_st->sdp_port, rtsp_st->sdp_ttl); if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) { err = AVERROR_INVALIDDATA; goto fail; } if ((err = rtsp_open_transport_ctx(s, rtsp_st))) goto fail; } return 0; fail: ff_rtsp_close_streams(s); ff_network_close(); return err; } static int sdp_read_close(AVFormatContext *s) { ff_rtsp_close_streams(s); ff_network_close(); return 0; } AVInputFormat sdp_demuxer = { "sdp", NULL_IF_CONFIG_SMALL("SDP"), sizeof(RTSPState), sdp_probe, sdp_read_header, rtsp_fetch_packet, sdp_read_close, };
123linslouis-android-video-cutter
jni/libavformat/rtsp.c
C
asf20
71,162
/* Electronic Arts Multimedia File Demuxer * Copyright (c) 2004 The ffmpeg Project * Copyright (c) 2006-2008 Peter Ross * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Electronic Arts Multimedia file demuxer (WVE/UV2/etc.) * by Robin Kay (komadori at gekkou.co.uk) */ #include "libavutil/intreadwrite.h" #include "avformat.h" #define SCHl_TAG MKTAG('S', 'C', 'H', 'l') #define SEAD_TAG MKTAG('S', 'E', 'A', 'D') /* Sxxx header */ #define SNDC_TAG MKTAG('S', 'N', 'D', 'C') /* Sxxx data */ #define SEND_TAG MKTAG('S', 'E', 'N', 'D') /* Sxxx end */ #define SHEN_TAG MKTAG('S', 'H', 'E', 'N') /* SxEN header */ #define SDEN_TAG MKTAG('S', 'D', 'E', 'N') /* SxEN data */ #define SEEN_TAG MKTAG('S', 'E', 'E', 'N') /* SxEN end */ #define ISNh_TAG MKTAG('1', 'S', 'N', 'h') /* 1SNx header */ #define EACS_TAG MKTAG('E', 'A', 'C', 'S') #define ISNd_TAG MKTAG('1', 'S', 'N', 'd') /* 1SNx data */ #define ISNe_TAG MKTAG('1', 'S', 'N', 'e') /* 1SNx end */ #define PT00_TAG MKTAG('P', 'T', 0x0, 0x0) #define GSTR_TAG MKTAG('G', 'S', 'T', 'R') #define SCDl_TAG MKTAG('S', 'C', 'D', 'l') #define SCEl_TAG MKTAG('S', 'C', 'E', 'l') #define kVGT_TAG MKTAG('k', 'V', 'G', 'T') /* TGV i-frame */ #define fVGT_TAG MKTAG('f', 'V', 'G', 'T') /* TGV p-frame */ #define mTCD_TAG MKTAG('m', 'T', 'C', 'D') /* MDEC */ #define MADk_TAG MKTAG('M', 'A', 'D', 'k') /* MAD i-frame */ #define MADm_TAG MKTAG('M', 'A', 'D', 'm') /* MAD p-frame */ #define MADe_TAG MKTAG('M', 'A', 'D', 'e') /* MAD lqp-frame */ #define MPCh_TAG MKTAG('M', 'P', 'C', 'h') /* MPEG2 */ #define TGQs_TAG MKTAG('T', 'G', 'Q', 's') /* TGQ i-frame (appears in .TGQ files) */ #define pQGT_TAG MKTAG('p', 'Q', 'G', 'T') /* TGQ i-frame (appears in .UV files) */ #define pIQT_TAG MKTAG('p', 'I', 'Q', 'T') /* TQI/UV2 i-frame (.UV2/.WVE) */ #define MVhd_TAG MKTAG('M', 'V', 'h', 'd') #define MV0K_TAG MKTAG('M', 'V', '0', 'K') #define MV0F_TAG MKTAG('M', 'V', '0', 'F') #define MVIh_TAG MKTAG('M', 'V', 'I', 'h') /* CMV header */ #define MVIf_TAG MKTAG('M', 'V', 'I', 'f') /* CMV i-frame */ typedef struct EaDemuxContext { int big_endian; enum CodecID video_codec; AVRational time_base; int width, height; int video_stream_index; enum CodecID audio_codec; int audio_stream_index; int audio_frame_counter; int bytes; int sample_rate; int num_channels; int num_samples; } EaDemuxContext; static uint32_t read_arbitary(ByteIOContext *pb) { uint8_t size, byte; int i; uint32_t word; size = get_byte(pb); word = 0; for (i = 0; i < size; i++) { byte = get_byte(pb); word <<= 8; word |= byte; } return word; } /* * Process PT/GSTR sound header * return 1 if success, 0 if invalid format, otherwise AVERROR_xxx */ static int process_audio_header_elements(AVFormatContext *s) { int inHeader = 1; EaDemuxContext *ea = s->priv_data; ByteIOContext *pb = s->pb; int compression_type = -1, revision = -1, revision2 = -1; ea->bytes = 2; ea->sample_rate = -1; ea->num_channels = 1; while (inHeader) { int inSubheader; uint8_t byte; byte = get_byte(pb); switch (byte) { case 0xFD: av_log (s, AV_LOG_DEBUG, "entered audio subheader\n"); inSubheader = 1; while (inSubheader) { uint8_t subbyte; subbyte = get_byte(pb); switch (subbyte) { case 0x80: revision = read_arbitary(pb); av_log (s, AV_LOG_DEBUG, "revision (element 0x80) set to 0x%08x\n", revision); break; case 0x82: ea->num_channels = read_arbitary(pb); av_log (s, AV_LOG_DEBUG, "num_channels (element 0x82) set to 0x%08x\n", ea->num_channels); break; case 0x83: compression_type = read_arbitary(pb); av_log (s, AV_LOG_DEBUG, "compression_type (element 0x83) set to 0x%08x\n", compression_type); break; case 0x84: ea->sample_rate = read_arbitary(pb); av_log (s, AV_LOG_DEBUG, "sample_rate (element 0x84) set to %i\n", ea->sample_rate); break; case 0x85: ea->num_samples = read_arbitary(pb); av_log (s, AV_LOG_DEBUG, "num_samples (element 0x85) set to 0x%08x\n", ea->num_samples); break; case 0x8A: av_log (s, AV_LOG_DEBUG, "element 0x%02x set to 0x%08x\n", subbyte, read_arbitary(pb)); av_log (s, AV_LOG_DEBUG, "exited audio subheader\n"); inSubheader = 0; break; case 0xA0: revision2 = read_arbitary(pb); av_log (s, AV_LOG_DEBUG, "revision2 (element 0xA0) set to 0x%08x\n", revision2); break; case 0xFF: av_log (s, AV_LOG_DEBUG, "end of header block reached (within audio subheader)\n"); inSubheader = 0; inHeader = 0; break; default: av_log (s, AV_LOG_DEBUG, "element 0x%02x set to 0x%08x\n", subbyte, read_arbitary(pb)); break; } } break; case 0xFF: av_log (s, AV_LOG_DEBUG, "end of header block reached\n"); inHeader = 0; break; default: av_log (s, AV_LOG_DEBUG, "header element 0x%02x set to 0x%08x\n", byte, read_arbitary(pb)); break; } } switch (compression_type) { case 0: ea->audio_codec = CODEC_ID_PCM_S16LE; break; case 7: ea->audio_codec = CODEC_ID_ADPCM_EA; break; case -1: switch (revision) { case 1: ea->audio_codec = CODEC_ID_ADPCM_EA_R1; break; case 2: ea->audio_codec = CODEC_ID_ADPCM_EA_R2; break; case 3: ea->audio_codec = CODEC_ID_ADPCM_EA_R3; break; case -1: break; default: av_log(s, AV_LOG_ERROR, "unsupported stream type; revision=%i\n", revision); return 0; } switch (revision2) { case 8: ea->audio_codec = CODEC_ID_PCM_S16LE_PLANAR; break; case 10: ea->audio_codec = CODEC_ID_ADPCM_EA_R2; break; case 16: ea->audio_codec = CODEC_ID_MP3; break; case -1: break; default: ea->audio_codec = CODEC_ID_NONE; av_log(s, AV_LOG_ERROR, "unsupported stream type; revision2=%i\n", revision2); return 0; } break; default: av_log(s, AV_LOG_ERROR, "unsupported stream type; compression_type=%i\n", compression_type); return 0; } if (ea->sample_rate == -1) ea->sample_rate = revision==3 ? 48000 : 22050; return 1; } /* * Process EACS sound header * return 1 if success, 0 if invalid format, otherwise AVERROR_xxx */ static int process_audio_header_eacs(AVFormatContext *s) { EaDemuxContext *ea = s->priv_data; ByteIOContext *pb = s->pb; int compression_type; ea->sample_rate = ea->big_endian ? get_be32(pb) : get_le32(pb); ea->bytes = get_byte(pb); /* 1=8-bit, 2=16-bit */ ea->num_channels = get_byte(pb); compression_type = get_byte(pb); url_fskip(pb, 13); switch (compression_type) { case 0: switch (ea->bytes) { case 1: ea->audio_codec = CODEC_ID_PCM_S8; break; case 2: ea->audio_codec = CODEC_ID_PCM_S16LE; break; } break; case 1: ea->audio_codec = CODEC_ID_PCM_MULAW; ea->bytes = 1; break; case 2: ea->audio_codec = CODEC_ID_ADPCM_IMA_EA_EACS; break; default: av_log (s, AV_LOG_ERROR, "unsupported stream type; audio compression_type=%i\n", compression_type); } return 1; } /* * Process SEAD sound header * return 1 if success, 0 if invalid format, otherwise AVERROR_xxx */ static int process_audio_header_sead(AVFormatContext *s) { EaDemuxContext *ea = s->priv_data; ByteIOContext *pb = s->pb; ea->sample_rate = get_le32(pb); ea->bytes = get_le32(pb); /* 1=8-bit, 2=16-bit */ ea->num_channels = get_le32(pb); ea->audio_codec = CODEC_ID_ADPCM_IMA_EA_SEAD; return 1; } static int process_video_header_mdec(AVFormatContext *s) { EaDemuxContext *ea = s->priv_data; ByteIOContext *pb = s->pb; url_fskip(pb, 4); ea->width = get_le16(pb); ea->height = get_le16(pb); ea->time_base = (AVRational){1,15}; ea->video_codec = CODEC_ID_MDEC; return 1; } static int process_video_header_vp6(AVFormatContext *s) { EaDemuxContext *ea = s->priv_data; ByteIOContext *pb = s->pb; url_fskip(pb, 16); ea->time_base.den = get_le32(pb); ea->time_base.num = get_le32(pb); ea->video_codec = CODEC_ID_VP6; return 1; } /* * Process EA file header * Returns 1 if the EA file is valid and successfully opened, 0 otherwise */ static int process_ea_header(AVFormatContext *s) { uint32_t blockid, size = 0; EaDemuxContext *ea = s->priv_data; ByteIOContext *pb = s->pb; int i; for (i=0; i<5 && (!ea->audio_codec || !ea->video_codec); i++) { unsigned int startpos = url_ftell(pb); int err = 0; blockid = get_le32(pb); size = get_le32(pb); if (i == 0) ea->big_endian = size > 0x000FFFFF; if (ea->big_endian) size = bswap_32(size); switch (blockid) { case ISNh_TAG: if (get_le32(pb) != EACS_TAG) { av_log (s, AV_LOG_ERROR, "unknown 1SNh headerid\n"); return 0; } err = process_audio_header_eacs(s); break; case SCHl_TAG : case SHEN_TAG : blockid = get_le32(pb); if (blockid == GSTR_TAG) { url_fskip(pb, 4); } else if ((blockid & 0xFFFF)!=PT00_TAG) { av_log (s, AV_LOG_ERROR, "unknown SCHl headerid\n"); return 0; } err = process_audio_header_elements(s); break; case SEAD_TAG: err = process_audio_header_sead(s); break; case MVIh_TAG : ea->video_codec = CODEC_ID_CMV; ea->time_base = (AVRational){0,0}; break; case kVGT_TAG: ea->video_codec = CODEC_ID_TGV; ea->time_base = (AVRational){0,0}; break; case mTCD_TAG : err = process_video_header_mdec(s); break; case MPCh_TAG: ea->video_codec = CODEC_ID_MPEG2VIDEO; break; case pQGT_TAG: case TGQs_TAG: ea->video_codec = CODEC_ID_TGQ; break; case pIQT_TAG: ea->video_codec = CODEC_ID_TQI; break; case MADk_TAG : ea->video_codec = CODEC_ID_MAD; break; case MVhd_TAG : err = process_video_header_vp6(s); break; } if (err < 0) { av_log(s, AV_LOG_ERROR, "error parsing header: %i\n", err); return err; } url_fseek(pb, startpos + size, SEEK_SET); } url_fseek(pb, 0, SEEK_SET); return 1; } static int ea_probe(AVProbeData *p) { switch (AV_RL32(&p->buf[0])) { case ISNh_TAG: case SCHl_TAG: case SEAD_TAG: case SHEN_TAG: case kVGT_TAG: case MADk_TAG: case MPCh_TAG: case MVhd_TAG: case MVIh_TAG: break; default: return 0; } if (AV_RL32(&p->buf[4]) > 0xfffff && AV_RB32(&p->buf[4]) > 0xfffff) return 0; return AVPROBE_SCORE_MAX; } static int ea_read_header(AVFormatContext *s, AVFormatParameters *ap) { EaDemuxContext *ea = s->priv_data; AVStream *st; if (!process_ea_header(s)) return AVERROR(EIO); if (ea->video_codec) { /* initialize the video decoder stream */ st = av_new_stream(s, 0); if (!st) return AVERROR(ENOMEM); ea->video_stream_index = st->index; st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = ea->video_codec; st->codec->codec_tag = 0; /* no fourcc */ st->codec->time_base = ea->time_base; st->codec->width = ea->width; st->codec->height = ea->height; } if (ea->audio_codec) { /* initialize the audio decoder stream */ st = av_new_stream(s, 0); if (!st) return AVERROR(ENOMEM); av_set_pts_info(st, 33, 1, ea->sample_rate); st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_id = ea->audio_codec; st->codec->codec_tag = 0; /* no tag */ st->codec->channels = ea->num_channels; st->codec->sample_rate = ea->sample_rate; st->codec->bits_per_coded_sample = ea->bytes * 8; st->codec->bit_rate = st->codec->channels * st->codec->sample_rate * st->codec->bits_per_coded_sample / 4; st->codec->block_align = st->codec->channels*st->codec->bits_per_coded_sample; ea->audio_stream_index = st->index; ea->audio_frame_counter = 0; } return 1; } static int ea_read_packet(AVFormatContext *s, AVPacket *pkt) { EaDemuxContext *ea = s->priv_data; ByteIOContext *pb = s->pb; int ret = 0; int packet_read = 0; unsigned int chunk_type, chunk_size; int key = 0; int av_uninit(num_samples); while (!packet_read) { chunk_type = get_le32(pb); chunk_size = (ea->big_endian ? get_be32(pb) : get_le32(pb)) - 8; switch (chunk_type) { /* audio data */ case ISNh_TAG: /* header chunk also contains data; skip over the header portion*/ url_fskip(pb, 32); chunk_size -= 32; case ISNd_TAG: case SCDl_TAG: case SNDC_TAG: case SDEN_TAG: if (!ea->audio_codec) { url_fskip(pb, chunk_size); break; } else if (ea->audio_codec == CODEC_ID_PCM_S16LE_PLANAR || ea->audio_codec == CODEC_ID_MP3) { num_samples = get_le32(pb); url_fskip(pb, 8); chunk_size -= 12; } ret = av_get_packet(pb, pkt, chunk_size); if (ret < 0) return ret; pkt->stream_index = ea->audio_stream_index; pkt->pts = 90000; pkt->pts *= ea->audio_frame_counter; pkt->pts /= ea->sample_rate; switch (ea->audio_codec) { case CODEC_ID_ADPCM_EA: /* 2 samples/byte, 1 or 2 samples per frame depending * on stereo; chunk also has 12-byte header */ ea->audio_frame_counter += ((chunk_size - 12) * 2) / ea->num_channels; break; case CODEC_ID_PCM_S16LE_PLANAR: case CODEC_ID_MP3: ea->audio_frame_counter += num_samples; break; default: ea->audio_frame_counter += chunk_size / (ea->bytes * ea->num_channels); } packet_read = 1; break; /* ending tag */ case 0: case ISNe_TAG: case SCEl_TAG: case SEND_TAG: case SEEN_TAG: ret = AVERROR(EIO); packet_read = 1; break; case MVIh_TAG: case kVGT_TAG: case pQGT_TAG: case TGQs_TAG: case MADk_TAG: key = AV_PKT_FLAG_KEY; case MVIf_TAG: case fVGT_TAG: case MADm_TAG: case MADe_TAG: url_fseek(pb, -8, SEEK_CUR); // include chunk preamble chunk_size += 8; goto get_video_packet; case mTCD_TAG: url_fseek(pb, 8, SEEK_CUR); // skip ea dct header chunk_size -= 8; goto get_video_packet; case MV0K_TAG: case MPCh_TAG: case pIQT_TAG: key = AV_PKT_FLAG_KEY; case MV0F_TAG: get_video_packet: ret = av_get_packet(pb, pkt, chunk_size); if (ret < 0) return ret; pkt->stream_index = ea->video_stream_index; pkt->flags |= key; packet_read = 1; break; default: url_fseek(pb, chunk_size, SEEK_CUR); break; } } return ret; } AVInputFormat ea_demuxer = { "ea", NULL_IF_CONFIG_SMALL("Electronic Arts Multimedia Format"), sizeof(EaDemuxContext), ea_probe, ea_read_header, ea_read_packet, };
123linslouis-android-video-cutter
jni/libavformat/electronicarts.c
C
asf20
17,875
/* * Smacker demuxer * Copyright (c) 2006 Konstantin Shishkov * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * Based on http://wiki.multimedia.cx/index.php?title=Smacker */ #include "libavutil/bswap.h" #include "libavutil/intreadwrite.h" #include "avformat.h" #define SMACKER_PAL 0x01 #define SMACKER_FLAG_RING_FRAME 0x01 enum SAudFlags { SMK_AUD_PACKED = 0x80000000, SMK_AUD_16BITS = 0x20000000, SMK_AUD_STEREO = 0x10000000, SMK_AUD_BINKAUD = 0x08000000, SMK_AUD_USEDCT = 0x04000000 }; typedef struct SmackerContext { /* Smacker file header */ uint32_t magic; uint32_t width, height; uint32_t frames; int pts_inc; uint32_t flags; uint32_t audio[7]; uint32_t treesize; uint32_t mmap_size, mclr_size, full_size, type_size; uint32_t rates[7]; uint32_t pad; /* frame info */ uint32_t *frm_size; uint8_t *frm_flags; /* internal variables */ int cur_frame; int is_ver4; int64_t cur_pts; /* current frame for demuxing */ uint8_t pal[768]; int indexes[7]; int videoindex; uint8_t *bufs[7]; int buf_sizes[7]; int stream_id[7]; int curstream; int64_t nextpos; int64_t aud_pts[7]; } SmackerContext; typedef struct SmackerFrame { int64_t pts; int stream; } SmackerFrame; /* palette used in Smacker */ static const uint8_t smk_pal[64] = { 0x00, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x18, 0x1C, 0x20, 0x24, 0x28, 0x2C, 0x30, 0x34, 0x38, 0x3C, 0x41, 0x45, 0x49, 0x4D, 0x51, 0x55, 0x59, 0x5D, 0x61, 0x65, 0x69, 0x6D, 0x71, 0x75, 0x79, 0x7D, 0x82, 0x86, 0x8A, 0x8E, 0x92, 0x96, 0x9A, 0x9E, 0xA2, 0xA6, 0xAA, 0xAE, 0xB2, 0xB6, 0xBA, 0xBE, 0xC3, 0xC7, 0xCB, 0xCF, 0xD3, 0xD7, 0xDB, 0xDF, 0xE3, 0xE7, 0xEB, 0xEF, 0xF3, 0xF7, 0xFB, 0xFF }; static int smacker_probe(AVProbeData *p) { if(p->buf[0] == 'S' && p->buf[1] == 'M' && p->buf[2] == 'K' && (p->buf[3] == '2' || p->buf[3] == '4')) return AVPROBE_SCORE_MAX; else return 0; } static int smacker_read_header(AVFormatContext *s, AVFormatParameters *ap) { ByteIOContext *pb = s->pb; SmackerContext *smk = s->priv_data; AVStream *st, *ast[7]; int i, ret; int tbase; /* read and check header */ smk->magic = get_le32(pb); if (smk->magic != MKTAG('S', 'M', 'K', '2') && smk->magic != MKTAG('S', 'M', 'K', '4')) return -1; smk->width = get_le32(pb); smk->height = get_le32(pb); smk->frames = get_le32(pb); smk->pts_inc = (int32_t)get_le32(pb); smk->flags = get_le32(pb); if(smk->flags & SMACKER_FLAG_RING_FRAME) smk->frames++; for(i = 0; i < 7; i++) smk->audio[i] = get_le32(pb); smk->treesize = get_le32(pb); if(smk->treesize >= UINT_MAX/4){ // smk->treesize + 16 must not overflow (this check is probably redundant) av_log(s, AV_LOG_ERROR, "treesize too large\n"); return -1; } //FIXME remove extradata "rebuilding" smk->mmap_size = get_le32(pb); smk->mclr_size = get_le32(pb); smk->full_size = get_le32(pb); smk->type_size = get_le32(pb); for(i = 0; i < 7; i++) smk->rates[i] = get_le32(pb); smk->pad = get_le32(pb); /* setup data */ if(smk->frames > 0xFFFFFF) { av_log(s, AV_LOG_ERROR, "Too many frames: %i\n", smk->frames); return -1; } smk->frm_size = av_malloc(smk->frames * 4); smk->frm_flags = av_malloc(smk->frames); smk->is_ver4 = (smk->magic != MKTAG('S', 'M', 'K', '2')); /* read frame info */ for(i = 0; i < smk->frames; i++) { smk->frm_size[i] = get_le32(pb); } for(i = 0; i < smk->frames; i++) { smk->frm_flags[i] = get_byte(pb); } /* init video codec */ st = av_new_stream(s, 0); if (!st) return -1; smk->videoindex = st->index; st->codec->width = smk->width; st->codec->height = smk->height; st->codec->pix_fmt = PIX_FMT_PAL8; st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = CODEC_ID_SMACKVIDEO; st->codec->codec_tag = smk->magic; /* Smacker uses 100000 as internal timebase */ if(smk->pts_inc < 0) smk->pts_inc = -smk->pts_inc; else smk->pts_inc *= 100; tbase = 100000; av_reduce(&tbase, &smk->pts_inc, tbase, smk->pts_inc, (1UL<<31)-1); av_set_pts_info(st, 33, smk->pts_inc, tbase); st->duration = smk->frames; /* handle possible audio streams */ for(i = 0; i < 7; i++) { smk->indexes[i] = -1; if(smk->rates[i] & 0xFFFFFF){ ast[i] = av_new_stream(s, 0); smk->indexes[i] = ast[i]->index; ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO; if (smk->rates[i] & SMK_AUD_BINKAUD) { ast[i]->codec->codec_id = CODEC_ID_BINKAUDIO_RDFT; } else if (smk->rates[i] & SMK_AUD_USEDCT) { ast[i]->codec->codec_id = CODEC_ID_BINKAUDIO_DCT; } else if (smk->rates[i] & SMK_AUD_PACKED){ ast[i]->codec->codec_id = CODEC_ID_SMACKAUDIO; ast[i]->codec->codec_tag = MKTAG('S', 'M', 'K', 'A'); } else { ast[i]->codec->codec_id = CODEC_ID_PCM_U8; } ast[i]->codec->channels = (smk->rates[i] & SMK_AUD_STEREO) ? 2 : 1; ast[i]->codec->sample_rate = smk->rates[i] & 0xFFFFFF; ast[i]->codec->bits_per_coded_sample = (smk->rates[i] & SMK_AUD_16BITS) ? 16 : 8; if(ast[i]->codec->bits_per_coded_sample == 16 && ast[i]->codec->codec_id == CODEC_ID_PCM_U8) ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE; av_set_pts_info(ast[i], 64, 1, ast[i]->codec->sample_rate * ast[i]->codec->channels * ast[i]->codec->bits_per_coded_sample / 8); } } /* load trees to extradata, they will be unpacked by decoder */ st->codec->extradata = av_malloc(smk->treesize + 16); st->codec->extradata_size = smk->treesize + 16; if(!st->codec->extradata){ av_log(s, AV_LOG_ERROR, "Cannot allocate %i bytes of extradata\n", smk->treesize + 16); av_free(smk->frm_size); av_free(smk->frm_flags); return -1; } ret = get_buffer(pb, st->codec->extradata + 16, st->codec->extradata_size - 16); if(ret != st->codec->extradata_size - 16){ av_free(smk->frm_size); av_free(smk->frm_flags); return AVERROR(EIO); } ((int32_t*)st->codec->extradata)[0] = le2me_32(smk->mmap_size); ((int32_t*)st->codec->extradata)[1] = le2me_32(smk->mclr_size); ((int32_t*)st->codec->extradata)[2] = le2me_32(smk->full_size); ((int32_t*)st->codec->extradata)[3] = le2me_32(smk->type_size); smk->curstream = -1; smk->nextpos = url_ftell(pb); return 0; } static int smacker_read_packet(AVFormatContext *s, AVPacket *pkt) { SmackerContext *smk = s->priv_data; int flags; int ret; int i; int frame_size = 0; int palchange = 0; int pos; if (url_feof(s->pb) || smk->cur_frame >= smk->frames) return AVERROR(EIO); /* if we demuxed all streams, pass another frame */ if(smk->curstream < 0) { url_fseek(s->pb, smk->nextpos, 0); frame_size = smk->frm_size[smk->cur_frame] & (~3); flags = smk->frm_flags[smk->cur_frame]; /* handle palette change event */ pos = url_ftell(s->pb); if(flags & SMACKER_PAL){ int size, sz, t, off, j, pos; uint8_t *pal = smk->pal; uint8_t oldpal[768]; memcpy(oldpal, pal, 768); size = get_byte(s->pb); size = size * 4 - 1; frame_size -= size; frame_size--; sz = 0; pos = url_ftell(s->pb) + size; while(sz < 256){ t = get_byte(s->pb); if(t & 0x80){ /* skip palette entries */ sz += (t & 0x7F) + 1; pal += ((t & 0x7F) + 1) * 3; } else if(t & 0x40){ /* copy with offset */ off = get_byte(s->pb) * 3; j = (t & 0x3F) + 1; while(j-- && sz < 256) { *pal++ = oldpal[off + 0]; *pal++ = oldpal[off + 1]; *pal++ = oldpal[off + 2]; sz++; off += 3; } } else { /* new entries */ *pal++ = smk_pal[t]; *pal++ = smk_pal[get_byte(s->pb) & 0x3F]; *pal++ = smk_pal[get_byte(s->pb) & 0x3F]; sz++; } } url_fseek(s->pb, pos, 0); palchange |= 1; } flags >>= 1; smk->curstream = -1; /* if audio chunks are present, put them to stack and retrieve later */ for(i = 0; i < 7; i++) { if(flags & 1) { int size; size = get_le32(s->pb) - 4; frame_size -= size; frame_size -= 4; smk->curstream++; smk->bufs[smk->curstream] = av_realloc(smk->bufs[smk->curstream], size); smk->buf_sizes[smk->curstream] = size; ret = get_buffer(s->pb, smk->bufs[smk->curstream], size); if(ret != size) return AVERROR(EIO); smk->stream_id[smk->curstream] = smk->indexes[i]; } flags >>= 1; } if (av_new_packet(pkt, frame_size + 768)) return AVERROR(ENOMEM); if(smk->frm_size[smk->cur_frame] & 1) palchange |= 2; pkt->data[0] = palchange; memcpy(pkt->data + 1, smk->pal, 768); ret = get_buffer(s->pb, pkt->data + 769, frame_size); if(ret != frame_size) return AVERROR(EIO); pkt->stream_index = smk->videoindex; pkt->size = ret + 769; smk->cur_frame++; smk->nextpos = url_ftell(s->pb); } else { if (av_new_packet(pkt, smk->buf_sizes[smk->curstream])) return AVERROR(ENOMEM); memcpy(pkt->data, smk->bufs[smk->curstream], smk->buf_sizes[smk->curstream]); pkt->size = smk->buf_sizes[smk->curstream]; pkt->stream_index = smk->stream_id[smk->curstream]; pkt->pts = smk->aud_pts[smk->curstream]; smk->aud_pts[smk->curstream] += AV_RL32(pkt->data); smk->curstream--; } return 0; } static int smacker_read_close(AVFormatContext *s) { SmackerContext *smk = s->priv_data; int i; for(i = 0; i < 7; i++) if(smk->bufs[i]) av_free(smk->bufs[i]); if(smk->frm_size) av_free(smk->frm_size); if(smk->frm_flags) av_free(smk->frm_flags); return 0; } AVInputFormat smacker_demuxer = { "smk", NULL_IF_CONFIG_SMALL("Smacker video"), sizeof(SmackerContext), smacker_probe, smacker_read_header, smacker_read_packet, smacker_read_close, };
123linslouis-android-video-cutter
jni/libavformat/smacker.c
C
asf20
11,748
/* * CD Graphics Demuxer * Copyright (c) 2009 Michael Tison * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avformat.h" #define CDG_PACKET_SIZE 24 static int read_header(AVFormatContext *s, AVFormatParameters *ap) { AVStream *vst; int ret; vst = av_new_stream(s, 0); if (!vst) return AVERROR(ENOMEM); vst->codec->codec_type = AVMEDIA_TYPE_VIDEO; vst->codec->codec_id = CODEC_ID_CDGRAPHICS; /// 75 sectors/sec * 4 packets/sector = 300 packets/sec av_set_pts_info(vst, 32, 1, 300); ret = url_fsize(s->pb); if (ret > 0) vst->duration = (ret * vst->time_base.den) / (CDG_PACKET_SIZE * 300); return 0; } static int read_packet(AVFormatContext *s, AVPacket *pkt) { int ret; ret = av_get_packet(s->pb, pkt, CDG_PACKET_SIZE); pkt->stream_index = 0; return ret; } AVInputFormat cdg_demuxer = { "cdg", NULL_IF_CONFIG_SMALL("CD Graphics Format"), 0, NULL, read_header, read_packet, .extensions = "cdg" };
123linslouis-android-video-cutter
jni/libavformat/cdg.c
C
asf20
1,742
/* * Ogg bitstream support * Luca Barbato <lu_zero@gentoo.org> * Based on tcvp implementation * */ /** Copyright (C) 2005 Michael Ahlberg, Måns Rullgård 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. **/ #include <stdio.h> #include "oggdec.h" #include "avformat.h" #include "vorbiscomment.h" #define MAX_PAGE_SIZE 65307 #define DECODER_BUFFER_SIZE MAX_PAGE_SIZE static const struct ogg_codec * const ogg_codecs[] = { &ff_skeleton_codec, &ff_dirac_codec, &ff_speex_codec, &ff_vorbis_codec, &ff_theora_codec, &ff_flac_codec, &ff_old_dirac_codec, &ff_old_flac_codec, &ff_ogm_video_codec, &ff_ogm_audio_codec, &ff_ogm_text_codec, &ff_ogm_old_codec, NULL }; //FIXME We could avoid some structure duplication static int ogg_save (AVFormatContext * s) { struct ogg *ogg = s->priv_data; struct ogg_state *ost = av_malloc(sizeof (*ost) + (ogg->nstreams-1) * sizeof (*ogg->streams)); int i; ost->pos = url_ftell (s->pb); ost->curidx = ogg->curidx; ost->next = ogg->state; ost->nstreams = ogg->nstreams; memcpy(ost->streams, ogg->streams, ogg->nstreams * sizeof(*ogg->streams)); for (i = 0; i < ogg->nstreams; i++){ struct ogg_stream *os = ogg->streams + i; os->buf = av_malloc (os->bufsize); memset (os->buf, 0, os->bufsize); memcpy (os->buf, ost->streams[i].buf, os->bufpos); } ogg->state = ost; return 0; } static int ogg_restore (AVFormatContext * s, int discard) { struct ogg *ogg = s->priv_data; ByteIOContext *bc = s->pb; struct ogg_state *ost = ogg->state; int i; if (!ost) return 0; ogg->state = ost->next; if (!discard){ for (i = 0; i < ogg->nstreams; i++) av_free (ogg->streams[i].buf); url_fseek (bc, ost->pos, SEEK_SET); ogg->curidx = ost->curidx; ogg->nstreams = ost->nstreams; memcpy(ogg->streams, ost->streams, ost->nstreams * sizeof(*ogg->streams)); } av_free (ost); return 0; } static int ogg_reset (struct ogg * ogg) { int i; for (i = 0; i < ogg->nstreams; i++){ struct ogg_stream *os = ogg->streams + i; os->bufpos = 0; os->pstart = 0; os->psize = 0; os->granule = -1; os->lastpts = AV_NOPTS_VALUE; os->lastdts = AV_NOPTS_VALUE; os->sync_pos = -1; os->page_pos = 0; os->nsegs = 0; os->segp = 0; os->incomplete = 0; } ogg->curidx = -1; return 0; } static const struct ogg_codec * ogg_find_codec (uint8_t * buf, int size) { int i; for (i = 0; ogg_codecs[i]; i++) if (size >= ogg_codecs[i]->magicsize && !memcmp (buf, ogg_codecs[i]->magic, ogg_codecs[i]->magicsize)) return ogg_codecs[i]; return NULL; } static int ogg_new_stream (AVFormatContext * s, uint32_t serial) { struct ogg *ogg = s->priv_data; int idx = ogg->nstreams++; AVStream *st; struct ogg_stream *os; ogg->streams = av_realloc (ogg->streams, ogg->nstreams * sizeof (*ogg->streams)); memset (ogg->streams + idx, 0, sizeof (*ogg->streams)); os = ogg->streams + idx; os->serial = serial; os->bufsize = DECODER_BUFFER_SIZE; os->buf = av_malloc(os->bufsize); os->header = -1; st = av_new_stream (s, idx); if (!st) return AVERROR(ENOMEM); av_set_pts_info(st, 64, 1, 1000000); return idx; } static int ogg_new_buf(struct ogg *ogg, int idx) { struct ogg_stream *os = ogg->streams + idx; uint8_t *nb = av_malloc(os->bufsize); int size = os->bufpos - os->pstart; if(os->buf){ memcpy(nb, os->buf + os->pstart, size); av_free(os->buf); } os->buf = nb; os->bufpos = size; os->pstart = 0; return 0; } static int ogg_read_page (AVFormatContext * s, int *str) { ByteIOContext *bc = s->pb; struct ogg *ogg = s->priv_data; struct ogg_stream *os; int i = 0; int flags, nsegs; uint64_t gp; uint32_t serial; uint32_t seq; uint32_t crc; int size, idx; uint8_t sync[4]; int sp = 0; if (get_buffer (bc, sync, 4) < 4) return -1; do{ int c; if (sync[sp & 3] == 'O' && sync[(sp + 1) & 3] == 'g' && sync[(sp + 2) & 3] == 'g' && sync[(sp + 3) & 3] == 'S') break; c = url_fgetc (bc); if (c < 0) return -1; sync[sp++ & 3] = c; }while (i++ < MAX_PAGE_SIZE); if (i >= MAX_PAGE_SIZE){ av_log (s, AV_LOG_INFO, "ogg, can't find sync word\n"); return -1; } if (url_fgetc (bc) != 0) /* version */ return -1; flags = url_fgetc (bc); gp = get_le64 (bc); serial = get_le32 (bc); seq = get_le32 (bc); crc = get_le32 (bc); nsegs = url_fgetc (bc); idx = ogg_find_stream (ogg, serial); if (idx < 0){ idx = ogg_new_stream (s, serial); if (idx < 0) return -1; } os = ogg->streams + idx; os->page_pos = url_ftell(bc) - 27; if(os->psize > 0) ogg_new_buf(ogg, idx); if (get_buffer (bc, os->segments, nsegs) < nsegs) return -1; os->nsegs = nsegs; os->segp = 0; size = 0; for (i = 0; i < nsegs; i++) size += os->segments[i]; if (flags & OGG_FLAG_CONT || os->incomplete){ if (!os->psize){ while (os->segp < os->nsegs){ int seg = os->segments[os->segp++]; os->pstart += seg; if (seg < 255) break; } os->sync_pos = os->page_pos; } }else{ os->psize = 0; os->sync_pos = os->page_pos; } if (os->bufsize - os->bufpos < size){ uint8_t *nb = av_malloc (os->bufsize *= 2); memcpy (nb, os->buf, os->bufpos); av_free (os->buf); os->buf = nb; } if (get_buffer (bc, os->buf + os->bufpos, size) < size) return -1; os->bufpos += size; os->granule = gp; os->flags = flags; if (str) *str = idx; return 0; } static int ogg_packet (AVFormatContext * s, int *str, int *dstart, int *dsize, int64_t *fpos) { struct ogg *ogg = s->priv_data; int idx, i; struct ogg_stream *os; int complete = 0; int segp = 0, psize = 0; #if 0 av_log (s, AV_LOG_DEBUG, "ogg_packet: curidx=%i\n", ogg->curidx); #endif do{ idx = ogg->curidx; while (idx < 0){ if (ogg_read_page (s, &idx) < 0) return -1; } os = ogg->streams + idx; #if 0 av_log (s, AV_LOG_DEBUG, "ogg_packet: idx=%d pstart=%d psize=%d segp=%d nsegs=%d\n", idx, os->pstart, os->psize, os->segp, os->nsegs); #endif if (!os->codec){ if (os->header < 0){ os->codec = ogg_find_codec (os->buf, os->bufpos); if (!os->codec){ os->header = 0; return 0; } }else{ return 0; } } segp = os->segp; psize = os->psize; while (os->segp < os->nsegs){ int ss = os->segments[os->segp++]; os->psize += ss; if (ss < 255){ complete = 1; break; } } if (!complete && os->segp == os->nsegs){ ogg->curidx = -1; os->incomplete = 1; } }while (!complete); #if 0 av_log (s, AV_LOG_DEBUG, "ogg_packet: idx %i, frame size %i, start %i\n", idx, os->psize, os->pstart); #endif if (os->granule == -1) av_log(s, AV_LOG_WARNING, "Page at %lld is missing granule\n", os->page_pos); ogg->curidx = idx; os->incomplete = 0; if (os->header) { os->header = os->codec->header (s, idx); if (!os->header){ os->segp = segp; os->psize = psize; if (!ogg->headers) s->data_offset = os->sync_pos; ogg->headers = 1; }else{ os->pstart += os->psize; os->psize = 0; } } else { os->pflags = 0; os->pduration = 0; if (os->codec && os->codec->packet) os->codec->packet (s, idx); if (str) *str = idx; if (dstart) *dstart = os->pstart; if (dsize) *dsize = os->psize; if (fpos) *fpos = os->sync_pos; os->pstart += os->psize; os->psize = 0; os->sync_pos = os->page_pos; } // determine whether there are more complete packets in this page // if not, the page's granule will apply to this packet os->page_end = 1; for (i = os->segp; i < os->nsegs; i++) if (os->segments[i] < 255) { os->page_end = 0; break; } if (os->segp == os->nsegs) ogg->curidx = -1; return 0; } static int ogg_get_headers (AVFormatContext * s) { struct ogg *ogg = s->priv_data; do{ if (ogg_packet (s, NULL, NULL, NULL, NULL) < 0) return -1; }while (!ogg->headers); #if 0 av_log (s, AV_LOG_DEBUG, "found headers\n"); #endif return 0; } static int ogg_get_length (AVFormatContext * s) { struct ogg *ogg = s->priv_data; int i; int64_t size, end; if(url_is_streamed(s->pb)) return 0; // already set if (s->duration != AV_NOPTS_VALUE) return 0; size = url_fsize(s->pb); if(size < 0) return 0; end = size > MAX_PAGE_SIZE? size - MAX_PAGE_SIZE: 0; ogg_save (s); url_fseek (s->pb, end, SEEK_SET); while (!ogg_read_page (s, &i)){ if (ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0 && ogg->streams[i].codec) { s->streams[i]->duration = ogg_gptopts (s, i, ogg->streams[i].granule, NULL); if (s->streams[i]->start_time != AV_NOPTS_VALUE) s->streams[i]->duration -= s->streams[i]->start_time; } } ogg_restore (s, 0); return 0; } static int ogg_read_header (AVFormatContext * s, AVFormatParameters * ap) { struct ogg *ogg = s->priv_data; int i; ogg->curidx = -1; //linear headers seek from start if (ogg_get_headers (s) < 0){ return -1; } for (i = 0; i < ogg->nstreams; i++) if (ogg->streams[i].header < 0) ogg->streams[i].codec = NULL; //linear granulepos seek from end ogg_get_length (s); //fill the extradata in the per codec callbacks return 0; } static int64_t ogg_calc_pts(AVFormatContext *s, int idx, int64_t *dts) { struct ogg *ogg = s->priv_data; struct ogg_stream *os = ogg->streams + idx; int64_t pts = AV_NOPTS_VALUE; if (dts) *dts = AV_NOPTS_VALUE; if (os->lastpts != AV_NOPTS_VALUE) { pts = os->lastpts; os->lastpts = AV_NOPTS_VALUE; } if (os->lastdts != AV_NOPTS_VALUE) { if (dts) *dts = os->lastdts; os->lastdts = AV_NOPTS_VALUE; } if (os->page_end) { if (os->granule != -1LL) { if (os->codec && os->codec->granule_is_start) pts = ogg_gptopts(s, idx, os->granule, dts); else os->lastpts = ogg_gptopts(s, idx, os->granule, &os->lastdts); os->granule = -1LL; } } return pts; } static int ogg_read_packet (AVFormatContext * s, AVPacket * pkt) { struct ogg *ogg; struct ogg_stream *os; int idx = -1; int pstart, psize; int64_t fpos, pts, dts; //Get an ogg packet retry: do{ if (ogg_packet (s, &idx, &pstart, &psize, &fpos) < 0) return AVERROR(EIO); }while (idx < 0 || !s->streams[idx]); ogg = s->priv_data; os = ogg->streams + idx; // pflags might not be set until after this pts = ogg_calc_pts(s, idx, &dts); if (os->keyframe_seek && !(os->pflags & AV_PKT_FLAG_KEY)) goto retry; os->keyframe_seek = 0; //Alloc a pkt if (av_new_packet (pkt, psize) < 0) return AVERROR(EIO); pkt->stream_index = idx; memcpy (pkt->data, os->buf + pstart, psize); pkt->pts = pts; pkt->dts = dts; pkt->flags = os->pflags; pkt->duration = os->pduration; pkt->pos = fpos; return psize; } static int ogg_read_close (AVFormatContext * s) { struct ogg *ogg = s->priv_data; int i; for (i = 0; i < ogg->nstreams; i++){ av_free (ogg->streams[i].buf); av_free (ogg->streams[i].private); } av_free (ogg->streams); return 0; } static int64_t ogg_read_timestamp (AVFormatContext * s, int stream_index, int64_t * pos_arg, int64_t pos_limit) { struct ogg *ogg = s->priv_data; struct ogg_stream *os = ogg->streams + stream_index; ByteIOContext *bc = s->pb; int64_t pts = AV_NOPTS_VALUE; int i; url_fseek(bc, *pos_arg, SEEK_SET); ogg_reset(ogg); while (url_ftell(bc) < pos_limit && !ogg_packet(s, &i, NULL, NULL, pos_arg)) { if (i == stream_index) { pts = ogg_calc_pts(s, i, NULL); if (os->keyframe_seek && !(os->pflags & AV_PKT_FLAG_KEY)) pts = AV_NOPTS_VALUE; } if (pts != AV_NOPTS_VALUE) break; } ogg_reset(ogg); return pts; } static int ogg_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { struct ogg *ogg = s->priv_data; struct ogg_stream *os = ogg->streams + stream_index; int ret; // Try seeking to a keyframe first. If this fails (very possible), // av_seek_frame will fall back to ignoring keyframes if (s->streams[stream_index]->codec->codec_type == AVMEDIA_TYPE_VIDEO && !(flags & AVSEEK_FLAG_ANY)) os->keyframe_seek = 1; ret = av_seek_frame_binary(s, stream_index, timestamp, flags); if (ret < 0) os->keyframe_seek = 0; return ret; } static int ogg_probe(AVProbeData *p) { if (p->buf[0] == 'O' && p->buf[1] == 'g' && p->buf[2] == 'g' && p->buf[3] == 'S' && p->buf[4] == 0x0 && p->buf[5] <= 0x7 ) return AVPROBE_SCORE_MAX; else return 0; } AVInputFormat ogg_demuxer = { "ogg", NULL_IF_CONFIG_SMALL("Ogg"), sizeof (struct ogg), ogg_probe, ogg_read_header, ogg_read_packet, ogg_read_close, ogg_read_seek, ogg_read_timestamp, .extensions = "ogg", .metadata_conv = ff_vorbiscomment_metadata_conv, .flags = AVFMT_GENERIC_INDEX, };
123linslouis-android-video-cutter
jni/libavformat/oggdec.c
C
asf20
15,713
/* * Buffered I/O for ffmpeg system * Copyright (c) 2000,2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/crc.h" #include "libavutil/intreadwrite.h" #include "avformat.h" #include "avio.h" #include <stdarg.h> #define IO_BUFFER_SIZE 32768 /** * Do seeks within this distance ahead of the current buffer by skipping * data instead of calling the protocol seek function, for seekable * protocols. */ #define SHORT_SEEK_THRESHOLD 4096 static void fill_buffer(ByteIOContext *s); #if LIBAVFORMAT_VERSION_MAJOR >= 53 static int url_resetbuf(ByteIOContext *s, int flags); #endif int init_put_byte(ByteIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int (*read_packet)(void *opaque, uint8_t *buf, int buf_size), int (*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t (*seek)(void *opaque, int64_t offset, int whence)) { s->buffer = buffer; s->buffer_size = buffer_size; s->buf_ptr = buffer; s->opaque = opaque; url_resetbuf(s, write_flag ? URL_WRONLY : URL_RDONLY); s->write_packet = write_packet; s->read_packet = read_packet; s->seek = seek; s->pos = 0; s->must_flush = 0; s->eof_reached = 0; s->error = 0; s->is_streamed = 0; s->max_packet_size = 0; s->update_checksum= NULL; if(!read_packet && !write_flag){ s->pos = buffer_size; s->buf_end = s->buffer + buffer_size; } s->read_pause = NULL; s->read_seek = NULL; return 0; } ByteIOContext *av_alloc_put_byte( unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int (*read_packet)(void *opaque, uint8_t *buf, int buf_size), int (*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t (*seek)(void *opaque, int64_t offset, int whence)) { ByteIOContext *s = av_mallocz(sizeof(ByteIOContext)); init_put_byte(s, buffer, buffer_size, write_flag, opaque, read_packet, write_packet, seek); return s; } static void flush_buffer(ByteIOContext *s) { if (s->buf_ptr > s->buffer) { if (s->write_packet && !s->error){ int ret= s->write_packet(s->opaque, s->buffer, s->buf_ptr - s->buffer); if(ret < 0){ s->error = ret; } } if(s->update_checksum){ s->checksum= s->update_checksum(s->checksum, s->checksum_ptr, s->buf_ptr - s->checksum_ptr); s->checksum_ptr= s->buffer; } s->pos += s->buf_ptr - s->buffer; } s->buf_ptr = s->buffer; } void put_byte(ByteIOContext *s, int b) { *(s->buf_ptr)++ = b; if (s->buf_ptr >= s->buf_end) flush_buffer(s); } void put_buffer(ByteIOContext *s, const unsigned char *buf, int size) { while (size > 0) { int len = FFMIN(s->buf_end - s->buf_ptr, size); memcpy(s->buf_ptr, buf, len); s->buf_ptr += len; if (s->buf_ptr >= s->buf_end) flush_buffer(s); buf += len; size -= len; } } void put_flush_packet(ByteIOContext *s) { flush_buffer(s); s->must_flush = 0; } int64_t url_fseek(ByteIOContext *s, int64_t offset, int whence) { int64_t offset1; int64_t pos; int force = whence & AVSEEK_FORCE; whence &= ~AVSEEK_FORCE; if(!s) return AVERROR(EINVAL); pos = s->pos - (s->write_flag ? 0 : (s->buf_end - s->buffer)); if (whence != SEEK_CUR && whence != SEEK_SET) return AVERROR(EINVAL); if (whence == SEEK_CUR) { offset1 = pos + (s->buf_ptr - s->buffer); if (offset == 0) return offset1; offset += offset1; } offset1 = offset - pos; if (!s->must_flush && offset1 >= 0 && offset1 <= (s->buf_end - s->buffer)) { /* can do the seek inside the buffer */ s->buf_ptr = s->buffer + offset1; } else if ((s->is_streamed || offset1 <= s->buf_end + SHORT_SEEK_THRESHOLD - s->buffer) && !s->write_flag && offset1 >= 0 && (whence != SEEK_END || force)) { while(s->pos < offset && !s->eof_reached) fill_buffer(s); if (s->eof_reached) return AVERROR_EOF; s->buf_ptr = s->buf_end + offset - s->pos; } else { int64_t res; #if CONFIG_MUXERS || CONFIG_NETWORK if (s->write_flag) { flush_buffer(s); s->must_flush = 1; } #endif /* CONFIG_MUXERS || CONFIG_NETWORK */ if (!s->seek) return AVERROR(EPIPE); if ((res = s->seek(s->opaque, offset, SEEK_SET)) < 0) return res; if (!s->write_flag) s->buf_end = s->buffer; s->buf_ptr = s->buffer; s->pos = offset; } s->eof_reached = 0; return offset; } void url_fskip(ByteIOContext *s, int64_t offset) { url_fseek(s, offset, SEEK_CUR); } int64_t url_ftell(ByteIOContext *s) { return url_fseek(s, 0, SEEK_CUR); } int64_t url_fsize(ByteIOContext *s) { int64_t size; if(!s) return AVERROR(EINVAL); if (!s->seek) return AVERROR(ENOSYS); size = s->seek(s->opaque, 0, AVSEEK_SIZE); if(size<0){ if ((size = s->seek(s->opaque, -1, SEEK_END)) < 0) return size; size++; s->seek(s->opaque, s->pos, SEEK_SET); } return size; } int url_feof(ByteIOContext *s) { if(!s) return 0; return s->eof_reached; } int url_ferror(ByteIOContext *s) { if(!s) return 0; return s->error; } void put_le32(ByteIOContext *s, unsigned int val) { put_byte(s, val); put_byte(s, val >> 8); put_byte(s, val >> 16); put_byte(s, val >> 24); } void put_be32(ByteIOContext *s, unsigned int val) { put_byte(s, val >> 24); put_byte(s, val >> 16); put_byte(s, val >> 8); put_byte(s, val); } void put_strz(ByteIOContext *s, const char *str) { if (str) put_buffer(s, (const unsigned char *) str, strlen(str) + 1); else put_byte(s, 0); } void put_le64(ByteIOContext *s, uint64_t val) { put_le32(s, (uint32_t)(val & 0xffffffff)); put_le32(s, (uint32_t)(val >> 32)); } void put_be64(ByteIOContext *s, uint64_t val) { put_be32(s, (uint32_t)(val >> 32)); put_be32(s, (uint32_t)(val & 0xffffffff)); } void put_le16(ByteIOContext *s, unsigned int val) { put_byte(s, val); put_byte(s, val >> 8); } void put_be16(ByteIOContext *s, unsigned int val) { put_byte(s, val >> 8); put_byte(s, val); } void put_le24(ByteIOContext *s, unsigned int val) { put_le16(s, val & 0xffff); put_byte(s, val >> 16); } void put_be24(ByteIOContext *s, unsigned int val) { put_be16(s, val >> 8); put_byte(s, val); } void put_tag(ByteIOContext *s, const char *tag) { while (*tag) { put_byte(s, *tag++); } } /* Input stream */ static void fill_buffer(ByteIOContext *s) { uint8_t *dst= !s->max_packet_size && s->buf_end - s->buffer < s->buffer_size ? s->buf_ptr : s->buffer; int len= s->buffer_size - (dst - s->buffer); int max_buffer_size = s->max_packet_size ? s->max_packet_size : IO_BUFFER_SIZE; assert(s->buf_ptr == s->buf_end); /* no need to do anything if EOF already reached */ if (s->eof_reached) return; if(s->update_checksum && dst == s->buffer){ if(s->buf_end > s->checksum_ptr) s->checksum= s->update_checksum(s->checksum, s->checksum_ptr, s->buf_end - s->checksum_ptr); s->checksum_ptr= s->buffer; } /* make buffer smaller in case it ended up large after probing */ if (s->buffer_size > max_buffer_size) { url_setbufsize(s, max_buffer_size); s->checksum_ptr = dst = s->buffer; len = s->buffer_size; } if(s->read_packet) len = s->read_packet(s->opaque, dst, len); else len = 0; if (len <= 0) { /* do not modify buffer if EOF reached so that a seek back can be done without rereading data */ s->eof_reached = 1; if(len<0) s->error= len; } else { s->pos += len; s->buf_ptr = dst; s->buf_end = dst + len; } } unsigned long ff_crc04C11DB7_update(unsigned long checksum, const uint8_t *buf, unsigned int len) { return av_crc(av_crc_get_table(AV_CRC_32_IEEE), checksum, buf, len); } unsigned long get_checksum(ByteIOContext *s) { s->checksum= s->update_checksum(s->checksum, s->checksum_ptr, s->buf_ptr - s->checksum_ptr); s->update_checksum= NULL; return s->checksum; } void init_checksum(ByteIOContext *s, unsigned long (*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len), unsigned long checksum) { s->update_checksum= update_checksum; if(s->update_checksum){ s->checksum= checksum; s->checksum_ptr= s->buf_ptr; } } /* XXX: put an inline version */ int get_byte(ByteIOContext *s) { if (s->buf_ptr < s->buf_end) { return *s->buf_ptr++; } else { fill_buffer(s); if (s->buf_ptr < s->buf_end) return *s->buf_ptr++; else return 0; } } int url_fgetc(ByteIOContext *s) { if (s->buf_ptr < s->buf_end) { return *s->buf_ptr++; } else { fill_buffer(s); if (s->buf_ptr < s->buf_end) return *s->buf_ptr++; else return URL_EOF; } } int get_buffer(ByteIOContext *s, unsigned char *buf, int size) { int len, size1; size1 = size; while (size > 0) { len = s->buf_end - s->buf_ptr; if (len > size) len = size; if (len == 0) { if(size > s->buffer_size && !s->update_checksum){ if(s->read_packet) len = s->read_packet(s->opaque, buf, size); if (len <= 0) { /* do not modify buffer if EOF reached so that a seek back can be done without rereading data */ s->eof_reached = 1; if(len<0) s->error= len; break; } else { s->pos += len; size -= len; buf += len; s->buf_ptr = s->buffer; s->buf_end = s->buffer/* + len*/; } }else{ fill_buffer(s); len = s->buf_end - s->buf_ptr; if (len == 0) break; } } else { memcpy(buf, s->buf_ptr, len); buf += len; s->buf_ptr += len; size -= len; } } if (size1 == size) { if (url_ferror(s)) return url_ferror(s); if (url_feof(s)) return AVERROR_EOF; } return size1 - size; } int get_partial_buffer(ByteIOContext *s, unsigned char *buf, int size) { int len; if(size<0) return -1; len = s->buf_end - s->buf_ptr; if (len == 0) { fill_buffer(s); len = s->buf_end - s->buf_ptr; } if (len > size) len = size; memcpy(buf, s->buf_ptr, len); s->buf_ptr += len; if (!len) { if (url_ferror(s)) return url_ferror(s); if (url_feof(s)) return AVERROR_EOF; } return len; } unsigned int get_le16(ByteIOContext *s) { unsigned int val; val = get_byte(s); val |= get_byte(s) << 8; return val; } unsigned int get_le24(ByteIOContext *s) { unsigned int val; val = get_le16(s); val |= get_byte(s) << 16; return val; } unsigned int get_le32(ByteIOContext *s) { unsigned int val; val = get_le16(s); val |= get_le16(s) << 16; return val; } uint64_t get_le64(ByteIOContext *s) { uint64_t val; val = (uint64_t)get_le32(s); val |= (uint64_t)get_le32(s) << 32; return val; } unsigned int get_be16(ByteIOContext *s) { unsigned int val; val = get_byte(s) << 8; val |= get_byte(s); return val; } unsigned int get_be24(ByteIOContext *s) { unsigned int val; val = get_be16(s) << 8; val |= get_byte(s); return val; } unsigned int get_be32(ByteIOContext *s) { unsigned int val; val = get_be16(s) << 16; val |= get_be16(s); return val; } char *get_strz(ByteIOContext *s, char *buf, int maxlen) { int i = 0; char c; while ((c = get_byte(s))) { if (i < maxlen-1) buf[i++] = c; } buf[i] = 0; /* Ensure null terminated, but may be truncated */ return buf; } uint64_t get_be64(ByteIOContext *s) { uint64_t val; val = (uint64_t)get_be32(s) << 32; val |= (uint64_t)get_be32(s); return val; } uint64_t ff_get_v(ByteIOContext *bc){ uint64_t val = 0; int tmp; do{ tmp = get_byte(bc); val= (val<<7) + (tmp&127); }while(tmp&128); return val; } int url_fdopen(ByteIOContext **s, URLContext *h) { uint8_t *buffer; int buffer_size, max_packet_size; max_packet_size = url_get_max_packet_size(h); if (max_packet_size) { buffer_size = max_packet_size; /* no need to bufferize more than one packet */ } else { buffer_size = IO_BUFFER_SIZE; } buffer = av_malloc(buffer_size); if (!buffer) return AVERROR(ENOMEM); *s = av_mallocz(sizeof(ByteIOContext)); if(!*s) { av_free(buffer); return AVERROR(ENOMEM); } if (init_put_byte(*s, buffer, buffer_size, (h->flags & URL_WRONLY || h->flags & URL_RDWR), h, url_read, url_write, url_seek) < 0) { av_free(buffer); av_freep(s); return AVERROR(EIO); } (*s)->is_streamed = h->is_streamed; (*s)->max_packet_size = max_packet_size; if(h->prot) { (*s)->read_pause = (int (*)(void *, int))h->prot->url_read_pause; (*s)->read_seek = (int64_t (*)(void *, int, int64_t, int))h->prot->url_read_seek; } return 0; } int url_setbufsize(ByteIOContext *s, int buf_size) { uint8_t *buffer; buffer = av_malloc(buf_size); if (!buffer) return AVERROR(ENOMEM); av_free(s->buffer); s->buffer = buffer; s->buffer_size = buf_size; s->buf_ptr = buffer; url_resetbuf(s, s->write_flag ? URL_WRONLY : URL_RDONLY); return 0; } #if LIBAVFORMAT_VERSION_MAJOR < 53 int url_resetbuf(ByteIOContext *s, int flags) #else static int url_resetbuf(ByteIOContext *s, int flags) #endif { #if LIBAVFORMAT_VERSION_MAJOR < 53 URLContext *h = s->opaque; if ((flags & URL_RDWR) || (h && h->flags != flags && !h->flags & URL_RDWR)) return AVERROR(EINVAL); #else assert(flags == URL_WRONLY || flags == URL_RDONLY); #endif if (flags & URL_WRONLY) { s->buf_end = s->buffer + s->buffer_size; s->write_flag = 1; } else { s->buf_end = s->buffer; s->write_flag = 0; } return 0; } int ff_rewind_with_probe_data(ByteIOContext *s, unsigned char *buf, int buf_size) { int64_t buffer_start; int buffer_size; int overlap, new_size; if (s->write_flag) return AVERROR(EINVAL); buffer_size = s->buf_end - s->buffer; /* the buffers must touch or overlap */ if ((buffer_start = s->pos - buffer_size) > buf_size) return AVERROR(EINVAL); overlap = buf_size - buffer_start; new_size = buf_size + buffer_size - overlap; if (new_size > buf_size) { if (!(buf = av_realloc(buf, new_size))) return AVERROR(ENOMEM); memcpy(buf + buf_size, s->buffer + overlap, buffer_size - overlap); buf_size = new_size; } av_free(s->buffer); s->buf_ptr = s->buffer = buf; s->pos = s->buffer_size = buf_size; s->buf_end = s->buf_ptr + buf_size; s->eof_reached = 0; s->must_flush = 0; return 0; } int url_fopen(ByteIOContext **s, const char *filename, int flags) { URLContext *h; int err; err = url_open(&h, filename, flags); if (err < 0) return err; err = url_fdopen(s, h); if (err < 0) { url_close(h); return err; } return 0; } int url_fclose(ByteIOContext *s) { URLContext *h = s->opaque; av_free(s->buffer); av_free(s); return url_close(h); } URLContext *url_fileno(ByteIOContext *s) { return s->opaque; } #if CONFIG_MUXERS int url_fprintf(ByteIOContext *s, const char *fmt, ...) { va_list ap; char buf[4096]; int ret; va_start(ap, fmt); ret = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); put_buffer(s, buf, strlen(buf)); return ret; } #endif //CONFIG_MUXERS char *url_fgets(ByteIOContext *s, char *buf, int buf_size) { int c; char *q; c = url_fgetc(s); if (c == EOF) return NULL; q = buf; for(;;) { if (c == EOF || c == '\n') break; if ((q - buf) < buf_size - 1) *q++ = c; c = url_fgetc(s); } if (buf_size > 0) *q = '\0'; return buf; } int url_fget_max_packet_size(ByteIOContext *s) { return s->max_packet_size; } int av_url_read_fpause(ByteIOContext *s, int pause) { if (!s->read_pause) return AVERROR(ENOSYS); return s->read_pause(s->opaque, pause); } int64_t av_url_read_fseek(ByteIOContext *s, int stream_index, int64_t timestamp, int flags) { URLContext *h = s->opaque; int64_t ret; if (!s->read_seek) return AVERROR(ENOSYS); ret = s->read_seek(h, stream_index, timestamp, flags); if(ret >= 0) { int64_t pos; s->buf_ptr = s->buf_end; // Flush buffer pos = s->seek(h, 0, SEEK_CUR); if (pos >= 0) s->pos = pos; else if (pos != AVERROR(ENOSYS)) ret = pos; } return ret; } /* url_open_dyn_buf and url_close_dyn_buf are used in rtp.c to send a response * back to the server even if CONFIG_MUXERS is false. */ #if CONFIG_MUXERS || CONFIG_NETWORK /* buffer handling */ int url_open_buf(ByteIOContext **s, uint8_t *buf, int buf_size, int flags) { int ret; *s = av_mallocz(sizeof(ByteIOContext)); if(!*s) return AVERROR(ENOMEM); ret = init_put_byte(*s, buf, buf_size, (flags & URL_WRONLY || flags & URL_RDWR), NULL, NULL, NULL, NULL); if(ret != 0) av_freep(s); return ret; } int url_close_buf(ByteIOContext *s) { put_flush_packet(s); return s->buf_ptr - s->buffer; } /* output in a dynamic buffer */ typedef struct DynBuffer { int pos, size, allocated_size; uint8_t *buffer; int io_buffer_size; uint8_t io_buffer[1]; } DynBuffer; static int dyn_buf_write(void *opaque, uint8_t *buf, int buf_size) { DynBuffer *d = opaque; unsigned new_size, new_allocated_size; /* reallocate buffer if needed */ new_size = d->pos + buf_size; new_allocated_size = d->allocated_size; if(new_size < d->pos || new_size > INT_MAX/2) return -1; while (new_size > new_allocated_size) { if (!new_allocated_size) new_allocated_size = new_size; else new_allocated_size += new_allocated_size / 2 + 1; } if (new_allocated_size > d->allocated_size) { d->buffer = av_realloc(d->buffer, new_allocated_size); if(d->buffer == NULL) return AVERROR(ENOMEM); d->allocated_size = new_allocated_size; } memcpy(d->buffer + d->pos, buf, buf_size); d->pos = new_size; if (d->pos > d->size) d->size = d->pos; return buf_size; } static int dyn_packet_buf_write(void *opaque, uint8_t *buf, int buf_size) { unsigned char buf1[4]; int ret; /* packetized write: output the header */ AV_WB32(buf1, buf_size); ret= dyn_buf_write(opaque, buf1, 4); if(ret < 0) return ret; /* then the data */ return dyn_buf_write(opaque, buf, buf_size); } static int64_t dyn_buf_seek(void *opaque, int64_t offset, int whence) { DynBuffer *d = opaque; if (whence == SEEK_CUR) offset += d->pos; else if (whence == SEEK_END) offset += d->size; if (offset < 0 || offset > 0x7fffffffLL) return -1; d->pos = offset; return 0; } static int url_open_dyn_buf_internal(ByteIOContext **s, int max_packet_size) { DynBuffer *d; int ret; unsigned io_buffer_size = max_packet_size ? max_packet_size : 1024; if(sizeof(DynBuffer) + io_buffer_size < io_buffer_size) return -1; d = av_mallocz(sizeof(DynBuffer) + io_buffer_size); if (!d) return AVERROR(ENOMEM); *s = av_mallocz(sizeof(ByteIOContext)); if(!*s) { av_free(d); return AVERROR(ENOMEM); } d->io_buffer_size = io_buffer_size; ret = init_put_byte(*s, d->io_buffer, io_buffer_size, 1, d, NULL, max_packet_size ? dyn_packet_buf_write : dyn_buf_write, max_packet_size ? NULL : dyn_buf_seek); if (ret == 0) { (*s)->max_packet_size = max_packet_size; } else { av_free(d); av_freep(s); } return ret; } int url_open_dyn_buf(ByteIOContext **s) { return url_open_dyn_buf_internal(s, 0); } int url_open_dyn_packet_buf(ByteIOContext **s, int max_packet_size) { if (max_packet_size <= 0) return -1; return url_open_dyn_buf_internal(s, max_packet_size); } int url_close_dyn_buf(ByteIOContext *s, uint8_t **pbuffer) { DynBuffer *d = s->opaque; int size; put_flush_packet(s); *pbuffer = d->buffer; size = d->size; av_free(d); av_free(s); return size; } #endif /* CONFIG_MUXERS || CONFIG_NETWORK */
123linslouis-android-video-cutter
jni/libavformat/aviobuf.c
C
asf20
22,632
/* * MXF demuxer. * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * References * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value * SMPTE 377M MXF File Format Specifications * SMPTE 378M Operational Pattern 1a * SMPTE 379M MXF Generic Container * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container * * Principle * Search for Track numbers which will identify essence element KLV packets. * Search for SourcePackage which define tracks which contains Track numbers. * Material Package contains tracks with reference to SourcePackage tracks. * Search for Descriptors (Picture, Sound) which contains codec info and parameters. * Assign Descriptors to correct Tracks. * * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext. * Metadata parsing resolves Strong References to objects. * * Simple demuxer, only OP1A supported and some files might not work at all. * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1 */ //#define DEBUG #include "libavutil/aes.h" #include "libavcodec/bytestream.h" #include "avformat.h" #include "mxf.h" typedef struct { UID uid; enum MXFMetadataSetType type; UID source_container_ul; } MXFCryptoContext; typedef struct { UID uid; enum MXFMetadataSetType type; UID source_package_uid; UID data_definition_ul; int64_t duration; int64_t start_position; int source_track_id; } MXFStructuralComponent; typedef struct { UID uid; enum MXFMetadataSetType type; UID data_definition_ul; UID *structural_components_refs; int structural_components_count; int64_t duration; } MXFSequence; typedef struct { UID uid; enum MXFMetadataSetType type; MXFSequence *sequence; /* mandatory, and only one */ UID sequence_ref; int track_id; uint8_t track_number[4]; AVRational edit_rate; } MXFTrack; typedef struct { UID uid; enum MXFMetadataSetType type; UID essence_container_ul; UID essence_codec_ul; AVRational sample_rate; AVRational aspect_ratio; int width; int height; int channels; int bits_per_sample; UID *sub_descriptors_refs; int sub_descriptors_count; int linked_track_id; uint8_t *extradata; int extradata_size; } MXFDescriptor; typedef struct { UID uid; enum MXFMetadataSetType type; } MXFIndexTableSegment; typedef struct { UID uid; enum MXFMetadataSetType type; UID package_uid; UID *tracks_refs; int tracks_count; MXFDescriptor *descriptor; /* only one */ UID descriptor_ref; } MXFPackage; typedef struct { UID uid; enum MXFMetadataSetType type; } MXFMetadataSet; typedef struct { UID *packages_refs; int packages_count; MXFMetadataSet **metadata_sets; int metadata_sets_count; AVFormatContext *fc; struct AVAES *aesc; uint8_t *local_tags; int local_tags_count; } MXFContext; enum MXFWrappingScheme { Frame, Clip, }; typedef struct { const UID key; int (*read)(); int ctx_size; enum MXFMetadataSetType type; } MXFMetadataReadTableEntry; /* partial keys to match */ static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 }; static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 }; static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 }; /* complete keys to match */ static const uint8_t mxf_crypto_source_container_ul[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x02,0x02,0x00,0x00,0x00 }; static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 }; static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 }; static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 }; #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y))) static int64_t klv_decode_ber_length(ByteIOContext *pb) { uint64_t size = get_byte(pb); if (size & 0x80) { /* long form */ int bytes_num = size & 0x7f; /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */ if (bytes_num > 8) return -1; size = 0; while (bytes_num--) size = size << 8 | get_byte(pb); } return size; } static int mxf_read_sync(ByteIOContext *pb, const uint8_t *key, unsigned size) { int i, b; for (i = 0; i < size && !url_feof(pb); i++) { b = get_byte(pb); if (b == key[0]) i = 0; else if (b != key[i]) i = -1; } return i == size; } static int klv_read_packet(KLVPacket *klv, ByteIOContext *pb) { if (!mxf_read_sync(pb, mxf_klv_key, 4)) return -1; klv->offset = url_ftell(pb) - 4; memcpy(klv->key, mxf_klv_key, 4); get_buffer(pb, klv->key + 4, 12); klv->length = klv_decode_ber_length(pb); return klv->length == -1 ? -1 : 0; } static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv) { int i; for (i = 0; i < s->nb_streams; i++) { MXFTrack *track = s->streams[i]->priv_data; /* SMPTE 379M 7.3 */ if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number))) return i; } /* return 0 if only one stream, for OP Atom files with 0 as track number */ return s->nb_streams == 1 ? 0 : -1; } /* XXX: use AVBitStreamFilter */ static int mxf_get_d10_aes3_packet(ByteIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length) { const uint8_t *buf_ptr, *end_ptr; uint8_t *data_ptr; int i; if (length > 61444) /* worst case PAL 1920 samples 8 channels */ return -1; av_new_packet(pkt, length); get_buffer(pb, pkt->data, length); data_ptr = pkt->data; end_ptr = pkt->data + length; buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */ for (; buf_ptr < end_ptr; ) { for (i = 0; i < st->codec->channels; i++) { uint32_t sample = bytestream_get_le32(&buf_ptr); if (st->codec->bits_per_coded_sample == 24) bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff); else bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff); } buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M } pkt->size = data_ptr - pkt->data; return 0; } static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv) { static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b}; MXFContext *mxf = s->priv_data; ByteIOContext *pb = s->pb; int64_t end = url_ftell(pb) + klv->length; uint64_t size; uint64_t orig_size; uint64_t plaintext_size; uint8_t ivec[16]; uint8_t tmpbuf[16]; int index; if (!mxf->aesc && s->key && s->keylen == 16) { mxf->aesc = av_malloc(av_aes_size); if (!mxf->aesc) return -1; av_aes_init(mxf->aesc, s->key, 128, 1); } // crypto context url_fskip(pb, klv_decode_ber_length(pb)); // plaintext offset klv_decode_ber_length(pb); plaintext_size = get_be64(pb); // source klv key klv_decode_ber_length(pb); get_buffer(pb, klv->key, 16); if (!IS_KLV_KEY(klv, mxf_essence_element_key)) return -1; index = mxf_get_stream_index(s, klv); if (index < 0) return -1; // source size klv_decode_ber_length(pb); orig_size = get_be64(pb); if (orig_size < plaintext_size) return -1; // enc. code size = klv_decode_ber_length(pb); if (size < 32 || size - 32 < orig_size) return -1; get_buffer(pb, ivec, 16); get_buffer(pb, tmpbuf, 16); if (mxf->aesc) av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1); if (memcmp(tmpbuf, checkv, 16)) av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n"); size -= 32; av_get_packet(pb, pkt, size); size -= plaintext_size; if (mxf->aesc) av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size], &pkt->data[plaintext_size], size >> 4, ivec, 1); pkt->size = orig_size; pkt->stream_index = index; url_fskip(pb, end - url_ftell(pb)); return 0; } static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt) { KLVPacket klv; while (!url_feof(s->pb)) { if (klv_read_packet(&klv, s->pb) < 0) return -1; PRINT_KEY(s, "read packet", klv.key); dprintf(s, "size %lld offset %#llx\n", klv.length, klv.offset); if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) { int res = mxf_decrypt_triplet(s, pkt, &klv); if (res < 0) { av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n"); return -1; } return 0; } if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) { int index = mxf_get_stream_index(s, &klv); if (index < 0) { av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12)); goto skip; } if (s->streams[index]->discard == AVDISCARD_ALL) goto skip; /* check for 8 channels AES3 element */ if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) { if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) { av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n"); return -1; } } else av_get_packet(s->pb, pkt, klv.length); pkt->stream_index = index; pkt->pos = klv.offset; return 0; } else skip: url_fskip(s->pb, klv.length); } return AVERROR_EOF; } static int mxf_read_primer_pack(MXFContext *mxf) { ByteIOContext *pb = mxf->fc->pb; int item_num = get_be32(pb); int item_len = get_be32(pb); if (item_len != 18) { av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n"); return -1; } if (item_num > UINT_MAX / item_len) return -1; mxf->local_tags_count = item_num; mxf->local_tags = av_malloc(item_num*item_len); if (!mxf->local_tags) return -1; get_buffer(pb, mxf->local_tags, item_num*item_len); return 0; } static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set) { if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets)) return AVERROR(ENOMEM); mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets)); if (!mxf->metadata_sets) return -1; mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set; mxf->metadata_sets_count++; return 0; } static int mxf_read_cryptographic_context(MXFCryptoContext *cryptocontext, ByteIOContext *pb, int tag, int size, UID uid) { if (size != 16) return -1; if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul)) get_buffer(pb, cryptocontext->source_container_ul, 16); return 0; } static int mxf_read_content_storage(MXFContext *mxf, ByteIOContext *pb, int tag) { switch (tag) { case 0x1901: mxf->packages_count = get_be32(pb); if (mxf->packages_count >= UINT_MAX / sizeof(UID)) return -1; mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID)); if (!mxf->packages_refs) return -1; url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */ get_buffer(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID)); break; } return 0; } static int mxf_read_source_clip(MXFStructuralComponent *source_clip, ByteIOContext *pb, int tag) { switch(tag) { case 0x0202: source_clip->duration = get_be64(pb); break; case 0x1201: source_clip->start_position = get_be64(pb); break; case 0x1101: /* UMID, only get last 16 bytes */ url_fskip(pb, 16); get_buffer(pb, source_clip->source_package_uid, 16); break; case 0x1102: source_clip->source_track_id = get_be32(pb); break; } return 0; } static int mxf_read_material_package(MXFPackage *package, ByteIOContext *pb, int tag) { switch(tag) { case 0x4403: package->tracks_count = get_be32(pb); if (package->tracks_count >= UINT_MAX / sizeof(UID)) return -1; package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID)); if (!package->tracks_refs) return -1; url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */ get_buffer(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID)); break; } return 0; } static int mxf_read_track(MXFTrack *track, ByteIOContext *pb, int tag) { switch(tag) { case 0x4801: track->track_id = get_be32(pb); break; case 0x4804: get_buffer(pb, track->track_number, 4); break; case 0x4B01: track->edit_rate.den = get_be32(pb); track->edit_rate.num = get_be32(pb); break; case 0x4803: get_buffer(pb, track->sequence_ref, 16); break; } return 0; } static int mxf_read_sequence(MXFSequence *sequence, ByteIOContext *pb, int tag) { switch(tag) { case 0x0202: sequence->duration = get_be64(pb); break; case 0x0201: get_buffer(pb, sequence->data_definition_ul, 16); break; case 0x1001: sequence->structural_components_count = get_be32(pb); if (sequence->structural_components_count >= UINT_MAX / sizeof(UID)) return -1; sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID)); if (!sequence->structural_components_refs) return -1; url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */ get_buffer(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID)); break; } return 0; } static int mxf_read_source_package(MXFPackage *package, ByteIOContext *pb, int tag) { switch(tag) { case 0x4403: package->tracks_count = get_be32(pb); if (package->tracks_count >= UINT_MAX / sizeof(UID)) return -1; package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID)); if (!package->tracks_refs) return -1; url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */ get_buffer(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID)); break; case 0x4401: /* UMID, only get last 16 bytes */ url_fskip(pb, 16); get_buffer(pb, package->package_uid, 16); break; case 0x4701: get_buffer(pb, package->descriptor_ref, 16); break; } return 0; } static int mxf_read_index_table_segment(MXFIndexTableSegment *segment, ByteIOContext *pb, int tag) { switch(tag) { case 0x3F05: dprintf(NULL, "EditUnitByteCount %d\n", get_be32(pb)); break; case 0x3F06: dprintf(NULL, "IndexSID %d\n", get_be32(pb)); break; case 0x3F07: dprintf(NULL, "BodySID %d\n", get_be32(pb)); break; case 0x3F0B: dprintf(NULL, "IndexEditRate %d/%d\n", get_be32(pb), get_be32(pb)); break; case 0x3F0C: dprintf(NULL, "IndexStartPosition %lld\n", get_be64(pb)); break; case 0x3F0D: dprintf(NULL, "IndexDuration %lld\n", get_be64(pb)); break; } return 0; } static void mxf_read_pixel_layout(ByteIOContext *pb, MXFDescriptor *descriptor) { int code; do { code = get_byte(pb); dprintf(NULL, "pixel layout: code %#x\n", code); switch (code) { case 0x52: /* R */ descriptor->bits_per_sample += get_byte(pb); break; case 0x47: /* G */ descriptor->bits_per_sample += get_byte(pb); break; case 0x42: /* B */ descriptor->bits_per_sample += get_byte(pb); break; default: get_byte(pb); } } while (code != 0); /* SMPTE 377M E.2.46 */ } static int mxf_read_generic_descriptor(MXFDescriptor *descriptor, ByteIOContext *pb, int tag, int size, UID uid) { switch(tag) { case 0x3F01: descriptor->sub_descriptors_count = get_be32(pb); if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID)) return -1; descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID)); if (!descriptor->sub_descriptors_refs) return -1; url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */ get_buffer(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID)); break; case 0x3004: get_buffer(pb, descriptor->essence_container_ul, 16); break; case 0x3006: descriptor->linked_track_id = get_be32(pb); break; case 0x3201: /* PictureEssenceCoding */ get_buffer(pb, descriptor->essence_codec_ul, 16); break; case 0x3203: descriptor->width = get_be32(pb); break; case 0x3202: descriptor->height = get_be32(pb); break; case 0x320E: descriptor->aspect_ratio.num = get_be32(pb); descriptor->aspect_ratio.den = get_be32(pb); break; case 0x3D03: descriptor->sample_rate.num = get_be32(pb); descriptor->sample_rate.den = get_be32(pb); break; case 0x3D06: /* SoundEssenceCompression */ get_buffer(pb, descriptor->essence_codec_ul, 16); break; case 0x3D07: descriptor->channels = get_be32(pb); break; case 0x3D01: descriptor->bits_per_sample = get_be32(pb); break; case 0x3401: mxf_read_pixel_layout(pb, descriptor); break; default: /* Private uid used by SONY C0023S01.mxf */ if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) { descriptor->extradata = av_malloc(size); if (!descriptor->extradata) return -1; descriptor->extradata_size = size; get_buffer(pb, descriptor->extradata, size); } break; } return 0; } /* * Match an uid independently of the version byte and up to len common bytes * Returns: boolean */ static int mxf_match_uid(const UID key, const UID uid, int len) { int i; for (i = 0; i < len; i++) { if (i != 7 && key[i] != uid[i]) return 0; } return 1; } static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid) { while (uls->uid[0]) { if(mxf_match_uid(uls->uid, *uid, uls->matching_len)) break; uls++; } return uls; } static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type) { int i; if (!strong_ref) return NULL; for (i = 0; i < mxf->metadata_sets_count; i++) { if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) && (type == AnyType || mxf->metadata_sets[i]->type == type)) { return mxf->metadata_sets[i]; } } return NULL; } static const MXFCodecUL mxf_essence_container_uls[] = { // video essence container uls { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */ { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, CODEC_ID_DVVIDEO }, /* DV 625 25mbps */ // sound essence container uls { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */ { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */ { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */ { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, CODEC_ID_NONE }, }; static int mxf_parse_structural_metadata(MXFContext *mxf) { MXFPackage *material_package = NULL; MXFPackage *temp_package = NULL; int i, j, k; dprintf(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count); /* TODO: handle multiple material packages (OP3x) */ for (i = 0; i < mxf->packages_count; i++) { material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage); if (material_package) break; } if (!material_package) { av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n"); return -1; } for (i = 0; i < material_package->tracks_count; i++) { MXFPackage *source_package = NULL; MXFTrack *material_track = NULL; MXFTrack *source_track = NULL; MXFTrack *temp_track = NULL; MXFDescriptor *descriptor = NULL; MXFStructuralComponent *component = NULL; UID *essence_container_ul = NULL; const MXFCodecUL *codec_ul = NULL; const MXFCodecUL *container_ul = NULL; AVStream *st; if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n"); continue; } if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n"); continue; } /* TODO: handle multiple source clips */ for (j = 0; j < material_track->sequence->structural_components_count; j++) { /* TODO: handle timecode component */ component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip); if (!component) continue; for (k = 0; k < mxf->packages_count; k++) { temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage); if (!temp_package) continue; if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) { source_package = temp_package; break; } } if (!source_package) { av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source package found\n", material_track->track_id); break; } for (k = 0; k < source_package->tracks_count; k++) { if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n"); return -1; } if (temp_track->track_id == component->source_track_id) { source_track = temp_track; break; } } if (!source_track) { av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id); break; } } if (!source_track) continue; st = av_new_stream(mxf->fc, source_track->track_id); if (!st) { av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n"); return -1; } st->priv_data = source_track; st->duration = component->duration; if (st->duration == -1) st->duration = AV_NOPTS_VALUE; st->start_time = component->start_position; av_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den); if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n"); return -1; } PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul); codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul); st->codec->codec_type = codec_ul->id; source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType); if (source_package->descriptor) { if (source_package->descriptor->type == MultipleDescriptor) { for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) { MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor); if (!sub_descriptor) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n"); continue; } if (sub_descriptor->linked_track_id == source_track->track_id) { descriptor = sub_descriptor; break; } } } else if (source_package->descriptor->type == Descriptor) descriptor = source_package->descriptor; } if (!descriptor) { av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index); continue; } PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul); PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul); essence_container_ul = &descriptor->essence_container_ul; /* HACK: replacing the original key with mxf_encrypted_essence_container * is not allowed according to s429-6, try to find correct information anyway */ if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) { av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n"); for (k = 0; k < mxf->metadata_sets_count; k++) { MXFMetadataSet *metadata = mxf->metadata_sets[k]; if (metadata->type == CryptoContext) { essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul; break; } } } /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */ codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul); st->codec->codec_id = codec_ul->id; if (descriptor->extradata) { st->codec->extradata = descriptor->extradata; st->codec->extradata_size = descriptor->extradata_size; } if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) { container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul); if (st->codec->codec_id == CODEC_ID_NONE) st->codec->codec_id = container_ul->id; st->codec->width = descriptor->width; st->codec->height = descriptor->height; st->codec->bits_per_coded_sample = descriptor->bits_per_sample; /* Uncompressed */ st->need_parsing = AVSTREAM_PARSE_HEADERS; } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) { container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul); if (st->codec->codec_id == CODEC_ID_NONE) st->codec->codec_id = container_ul->id; st->codec->channels = descriptor->channels; st->codec->bits_per_coded_sample = descriptor->bits_per_sample; st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den; /* TODO: implement CODEC_ID_RAWAUDIO */ if (st->codec->codec_id == CODEC_ID_PCM_S16LE) { if (descriptor->bits_per_sample == 24) st->codec->codec_id = CODEC_ID_PCM_S24LE; else if (descriptor->bits_per_sample == 32) st->codec->codec_id = CODEC_ID_PCM_S32LE; } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) { if (descriptor->bits_per_sample == 24) st->codec->codec_id = CODEC_ID_PCM_S24BE; else if (descriptor->bits_per_sample == 32) st->codec->codec_id = CODEC_ID_PCM_S32BE; } else if (st->codec->codec_id == CODEC_ID_MP2) { st->need_parsing = AVSTREAM_PARSE_FULL; } } if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) { av_log(mxf->fc, AV_LOG_WARNING, "only frame wrapped mappings are correctly supported\n"); st->need_parsing = AVSTREAM_PARSE_FULL; } } return 0; } static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = { { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Generic Sound */ { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */ { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */ { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG 2 Video */ { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */ { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */ { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */ { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */ { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment }, { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType }, }; static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, int (*read_child)(), int ctx_size, enum MXFMetadataSetType type) { ByteIOContext *pb = mxf->fc->pb; MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf; uint64_t klv_end = url_ftell(pb) + klv->length; if (!ctx) return -1; while (url_ftell(pb) + 4 < klv_end) { int tag = get_be16(pb); int size = get_be16(pb); /* KLV specified by 0x53 */ uint64_t next = url_ftell(pb) + size; UID uid = {0}; dprintf(mxf->fc, "local tag %#04x size %d\n", tag, size); if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */ av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag); continue; } if (tag > 0x7FFF) { /* dynamic tag */ int i; for (i = 0; i < mxf->local_tags_count; i++) { int local_tag = AV_RB16(mxf->local_tags+i*18); if (local_tag == tag) { memcpy(uid, mxf->local_tags+i*18+2, 16); dprintf(mxf->fc, "local tag %#04x\n", local_tag); PRINT_KEY(mxf->fc, "uid", uid); } } } if (ctx_size && tag == 0x3C0A) get_buffer(pb, ctx->uid, 16); else if (read_child(ctx, pb, tag, size, uid) < 0) return -1; url_fseek(pb, next, SEEK_SET); } if (ctx_size) ctx->type = type; return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0; } static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap) { MXFContext *mxf = s->priv_data; KLVPacket klv; if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) { av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n"); return -1; } url_fseek(s->pb, -14, SEEK_CUR); mxf->fc = s; while (!url_feof(s->pb)) { const MXFMetadataReadTableEntry *metadata; if (klv_read_packet(&klv, s->pb) < 0) return -1; PRINT_KEY(s, "read header", klv.key); dprintf(s, "size %lld offset %#llx\n", klv.length, klv.offset); if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) || IS_KLV_KEY(klv.key, mxf_essence_element_key)) { /* FIXME avoid seek */ url_fseek(s->pb, klv.offset, SEEK_SET); break; } for (metadata = mxf_metadata_read_table; metadata->read; metadata++) { if (IS_KLV_KEY(klv.key, metadata->key)) { int (*read)() = klv.key[5] == 0x53 ? mxf_read_local_tags : metadata->read; if (read(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type) < 0) { av_log(s, AV_LOG_ERROR, "error reading header metadata\n"); return -1; } break; } } if (!metadata->read) url_fskip(s->pb, klv.length); } return mxf_parse_structural_metadata(mxf); } static int mxf_read_close(AVFormatContext *s) { MXFContext *mxf = s->priv_data; int i; av_freep(&mxf->packages_refs); for (i = 0; i < s->nb_streams; i++) s->streams[i]->priv_data = NULL; for (i = 0; i < mxf->metadata_sets_count; i++) { switch (mxf->metadata_sets[i]->type) { case MultipleDescriptor: av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs); break; case Sequence: av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs); break; case SourcePackage: case MaterialPackage: av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs); break; default: break; } av_freep(&mxf->metadata_sets[i]); } av_freep(&mxf->metadata_sets); av_freep(&mxf->aesc); av_freep(&mxf->local_tags); return 0; } static int mxf_probe(AVProbeData *p) { uint8_t *bufp = p->buf; uint8_t *end = p->buf + p->buf_size; if (p->buf_size < sizeof(mxf_header_partition_pack_key)) return 0; /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */ end -= sizeof(mxf_header_partition_pack_key); for (; bufp < end; bufp++) { if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key)) return AVPROBE_SCORE_MAX; } return 0; } /* rudimentary byte seek */ /* XXX: use MXF Index */ static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { AVStream *st = s->streams[stream_index]; int64_t seconds; if (!s->bit_rate) return -1; if (sample_time < 0) sample_time = 0; seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den); url_fseek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET); av_update_cur_dts(s, st, sample_time); return 0; } AVInputFormat mxf_demuxer = { "mxf", NULL_IF_CONFIG_SMALL("Material eXchange Format"), sizeof(MXFContext), mxf_probe, mxf_read_header, mxf_read_packet, mxf_read_close, mxf_read_seek, };
123linslouis-android-video-cutter
jni/libavformat/mxfdec.c
C
asf20
38,764
/* * RTSP definitions * copyright (c) 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_RTSPCODES_H #define AVFORMAT_RTSPCODES_H /** RTSP handling */ enum RTSPStatusCode { RTSP_STATUS_OK =200, /**< OK */ RTSP_STATUS_METHOD =405, /**< Method Not Allowed */ RTSP_STATUS_BANDWIDTH =453, /**< Not Enough Bandwidth */ RTSP_STATUS_SESSION =454, /**< Session Not Found */ RTSP_STATUS_STATE =455, /**< Method Not Valid in This State */ RTSP_STATUS_AGGREGATE =459, /**< Aggregate operation not allowed */ RTSP_STATUS_ONLY_AGGREGATE =460, /**< Only aggregate operation allowed */ RTSP_STATUS_TRANSPORT =461, /**< Unsupported transport */ RTSP_STATUS_INTERNAL =500, /**< Internal Server Error */ RTSP_STATUS_SERVICE =503, /**< Service Unavailable */ RTSP_STATUS_VERSION =505, /**< RTSP Version not supported */ }; #endif /* AVFORMAT_RTSPCODES_H */
123linslouis-android-video-cutter
jni/libavformat/rtspcodes.h
C
asf20
1,675
/* * UDP prototype streaming system * Copyright (c) 2000, 2001, 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * UDP protocol */ #define _BSD_SOURCE /* Needed for using struct ip_mreq with recent glibc */ #include "avformat.h" #include <unistd.h> #include "internal.h" #include "network.h" #include "os_support.h" #if HAVE_SYS_SELECT_H #include <sys/select.h> #endif #include <sys/time.h> #ifndef IPV6_ADD_MEMBERSHIP #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP #endif #ifndef IN_MULTICAST #define IN_MULTICAST(a) ((((uint32_t)(a)) & 0xf0000000) == 0xe0000000) #endif #ifndef IN6_IS_ADDR_MULTICAST #define IN6_IS_ADDR_MULTICAST(a) (((uint8_t *) (a))[0] == 0xff) #endif typedef struct { int udp_fd; int ttl; int buffer_size; int is_multicast; int local_port; int reuse_socket; struct sockaddr_storage dest_addr; int dest_addr_len; } UDPContext; #define UDP_TX_BUF_SIZE 32768 #define UDP_MAX_PKT_SIZE 65536 static int udp_set_multicast_ttl(int sockfd, int mcastTTL, struct sockaddr *addr) { #ifdef IP_MULTICAST_TTL if (addr->sa_family == AF_INET) { if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) { av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno)); return -1; } } #endif #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS) if (addr->sa_family == AF_INET6) { if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) { av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno)); return -1; } } #endif return 0; } static int udp_join_multicast_group(int sockfd, struct sockaddr *addr) { #ifdef IP_ADD_MEMBERSHIP if (addr->sa_family == AF_INET) { struct ip_mreq mreq; mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr; mreq.imr_interface.s_addr= INADDR_ANY; if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) { av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno)); return -1; } } #endif #if HAVE_STRUCT_IPV6_MREQ if (addr->sa_family == AF_INET6) { struct ipv6_mreq mreq6; memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr)); mreq6.ipv6mr_interface= 0; if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) { av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno)); return -1; } } #endif return 0; } static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr) { #ifdef IP_DROP_MEMBERSHIP if (addr->sa_family == AF_INET) { struct ip_mreq mreq; mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr; mreq.imr_interface.s_addr= INADDR_ANY; if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) { av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno)); return -1; } } #endif #if HAVE_STRUCT_IPV6_MREQ if (addr->sa_family == AF_INET6) { struct ipv6_mreq mreq6; memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr)); mreq6.ipv6mr_interface= 0; if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) { av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno)); return -1; } } #endif return 0; } static struct addrinfo* udp_resolve_host(const char *hostname, int port, int type, int family, int flags) { struct addrinfo hints, *res = 0; int error; char sport[16]; const char *node = 0, *service = "0"; if (port > 0) { snprintf(sport, sizeof(sport), "%d", port); service = sport; } if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) { node = hostname; } memset(&hints, 0, sizeof(hints)); hints.ai_socktype = type; hints.ai_family = family; hints.ai_flags = flags; if ((error = getaddrinfo(node, service, &hints, &res))) { res = NULL; av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error)); } return res; } static int udp_set_url(struct sockaddr_storage *addr, const char *hostname, int port) { struct addrinfo *res0; int addr_len; res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0); if (res0 == 0) return AVERROR(EIO); memcpy(addr, res0->ai_addr, res0->ai_addrlen); addr_len = res0->ai_addrlen; freeaddrinfo(res0); return addr_len; } static int is_multicast_address(struct sockaddr_storage *addr) { if (addr->ss_family == AF_INET) { return IN_MULTICAST(ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr)); } #if HAVE_STRUCT_SOCKADDR_IN6 if (addr->ss_family == AF_INET6) { return IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)addr)->sin6_addr); } #endif return 0; } static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr, int *addr_len) { int udp_fd = -1; struct addrinfo *res0 = NULL, *res = NULL; int family = AF_UNSPEC; if (((struct sockaddr *) &s->dest_addr)->sa_family) family = ((struct sockaddr *) &s->dest_addr)->sa_family; res0 = udp_resolve_host(0, s->local_port, SOCK_DGRAM, family, AI_PASSIVE); if (res0 == 0) goto fail; for (res = res0; res; res=res->ai_next) { udp_fd = socket(res->ai_family, SOCK_DGRAM, 0); if (udp_fd > 0) break; av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno)); } if (udp_fd < 0) goto fail; memcpy(addr, res->ai_addr, res->ai_addrlen); *addr_len = res->ai_addrlen; freeaddrinfo(res0); return udp_fd; fail: if (udp_fd >= 0) closesocket(udp_fd); if(res0) freeaddrinfo(res0); return -1; } static int udp_port(struct sockaddr_storage *addr, int addr_len) { char sbuf[sizeof(int)*3+1]; if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) { av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno)); return -1; } return strtol(sbuf, NULL, 10); } /** * If no filename is given to av_open_input_file because you want to * get the local port first, then you must call this function to set * the remote server address. * * url syntax: udp://host:port[?option=val...] * option: 'ttl=n' : set the ttl value (for multicast only) * 'localport=n' : set the local port * 'pkt_size=n' : set max packet size * 'reuse=1' : enable reusing the socket * * @param s1 media file context * @param uri of the remote server * @return zero if no error. */ int udp_set_remote_url(URLContext *h, const char *uri) { UDPContext *s = h->priv_data; char hostname[256]; int port; ff_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri); /* set the destination address */ s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port); if (s->dest_addr_len < 0) { return AVERROR(EIO); } s->is_multicast = is_multicast_address(&s->dest_addr); return 0; } /** * Return the local port used by the UDP connexion * @param s1 media file context * @return the local port number */ int udp_get_local_port(URLContext *h) { UDPContext *s = h->priv_data; return s->local_port; } /** * Return the udp file handle for select() usage to wait for several RTP * streams at the same time. * @param h media file context */ #if (LIBAVFORMAT_VERSION_MAJOR >= 53) static #endif int udp_get_file_handle(URLContext *h) { UDPContext *s = h->priv_data; return s->udp_fd; } /* put it in UDP context */ /* return non zero if error */ static int udp_open(URLContext *h, const char *uri, int flags) { char hostname[1024]; int port, udp_fd = -1, tmp, bind_ret = -1; UDPContext *s = NULL; int is_output; const char *p; char buf[256]; struct sockaddr_storage my_addr; int len; h->is_streamed = 1; h->max_packet_size = 1472; is_output = (flags & URL_WRONLY); s = av_mallocz(sizeof(UDPContext)); if (!s) return AVERROR(ENOMEM); h->priv_data = s; s->ttl = 16; s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE; p = strchr(uri, '?'); if (p) { s->reuse_socket = find_info_tag(buf, sizeof(buf), "reuse", p); if (find_info_tag(buf, sizeof(buf), "ttl", p)) { s->ttl = strtol(buf, NULL, 10); } if (find_info_tag(buf, sizeof(buf), "localport", p)) { s->local_port = strtol(buf, NULL, 10); } if (find_info_tag(buf, sizeof(buf), "pkt_size", p)) { h->max_packet_size = strtol(buf, NULL, 10); } if (find_info_tag(buf, sizeof(buf), "buffer_size", p)) { s->buffer_size = strtol(buf, NULL, 10); } } /* fill the dest addr */ ff_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri); /* XXX: fix ff_url_split */ if (hostname[0] == '\0' || hostname[0] == '?') { /* only accepts null hostname if input */ if (flags & URL_WRONLY) goto fail; } else { udp_set_remote_url(h, uri); } if (s->is_multicast && !(h->flags & URL_WRONLY)) s->local_port = port; udp_fd = udp_socket_create(s, &my_addr, &len); if (udp_fd < 0) goto fail; if (s->reuse_socket) if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0) goto fail; /* the bind is needed to give a port to the socket now */ /* if multicast, try the multicast address bind first */ if (s->is_multicast && !(h->flags & URL_WRONLY)) { bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len); } /* bind to the local address if not multicast or if the multicast * bind failed */ if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) goto fail; len = sizeof(my_addr); getsockname(udp_fd, (struct sockaddr *)&my_addr, &len); s->local_port = udp_port(&my_addr, len); if (s->is_multicast) { if (h->flags & URL_WRONLY) { /* output */ if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0) goto fail; } else { /* input */ if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0) goto fail; } } if (is_output) { /* limit the tx buf size to limit latency */ tmp = s->buffer_size; if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) { av_log(NULL, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno)); goto fail; } } else { /* set udp recv buffer size to the largest possible udp packet size to * avoid losing data on OSes that set this too low by default. */ tmp = s->buffer_size; if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) { av_log(NULL, AV_LOG_WARNING, "setsockopt(SO_RECVBUF): %s\n", strerror(errno)); } /* make the socket non-blocking */ ff_socket_nonblock(udp_fd, 1); } s->udp_fd = udp_fd; return 0; fail: if (udp_fd >= 0) closesocket(udp_fd); av_free(s); return AVERROR(EIO); } static int udp_read(URLContext *h, uint8_t *buf, int size) { UDPContext *s = h->priv_data; int len; fd_set rfds; int ret; struct timeval tv; for(;;) { if (url_interrupt_cb()) return AVERROR(EINTR); FD_ZERO(&rfds); FD_SET(s->udp_fd, &rfds); tv.tv_sec = 0; tv.tv_usec = 100 * 1000; ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv); if (ret < 0) { if (ff_neterrno() == FF_NETERROR(EINTR)) continue; return AVERROR(EIO); } if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds))) continue; len = recv(s->udp_fd, buf, size, 0); if (len < 0) { if (ff_neterrno() != FF_NETERROR(EAGAIN) && ff_neterrno() != FF_NETERROR(EINTR)) return AVERROR(EIO); } else { break; } } return len; } static int udp_write(URLContext *h, uint8_t *buf, int size) { UDPContext *s = h->priv_data; int ret; for(;;) { ret = sendto (s->udp_fd, buf, size, 0, (struct sockaddr *) &s->dest_addr, s->dest_addr_len); if (ret < 0) { if (ff_neterrno() != FF_NETERROR(EINTR) && ff_neterrno() != FF_NETERROR(EAGAIN)) return AVERROR(EIO); } else { break; } } return size; } static int udp_close(URLContext *h) { UDPContext *s = h->priv_data; if (s->is_multicast && !(h->flags & URL_WRONLY)) udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr); closesocket(s->udp_fd); av_free(s); return 0; } URLProtocol udp_protocol = { "udp", udp_open, udp_read, udp_write, NULL, /* seek */ udp_close, .url_get_file_handle = udp_get_file_handle, };
123linslouis-android-video-cutter
jni/libavformat/udp.c
C
asf20
14,652
/* * ASF muxer * Copyright (c) 2000, 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avformat.h" #include "metadata.h" #include "riff.h" #include "asf.h" #undef NDEBUG #include <assert.h> #define ASF_INDEXED_INTERVAL 10000000 #define ASF_INDEX_BLOCK 600 #define ASF_PACKET_ERROR_CORRECTION_DATA_SIZE 0x2 #define ASF_PACKET_ERROR_CORRECTION_FLAGS (\ ASF_PACKET_FLAG_ERROR_CORRECTION_PRESENT | \ ASF_PACKET_ERROR_CORRECTION_DATA_SIZE\ ) #if (ASF_PACKET_ERROR_CORRECTION_FLAGS != 0) # define ASF_PACKET_ERROR_CORRECTION_FLAGS_FIELD_SIZE 1 #else # define ASF_PACKET_ERROR_CORRECTION_FLAGS_FIELD_SIZE 0 #endif #define ASF_PPI_PROPERTY_FLAGS (\ ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_BYTE | \ ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_DWORD | \ ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_BYTE | \ ASF_PL_FLAG_STREAM_NUMBER_LENGTH_FIELD_IS_BYTE \ ) #define ASF_PPI_LENGTH_TYPE_FLAGS 0 #define ASF_PAYLOAD_FLAGS ASF_PL_FLAG_PAYLOAD_LENGTH_FIELD_IS_WORD #if (ASF_PPI_FLAG_SEQUENCE_FIELD_IS_BYTE == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_SEQUENCE_FIELD_SIZE)) # define ASF_PPI_SEQUENCE_FIELD_SIZE 1 #endif #if (ASF_PPI_FLAG_SEQUENCE_FIELD_IS_WORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_SEQUENCE_FIELD_SIZE)) # define ASF_PPI_SEQUENCE_FIELD_SIZE 2 #endif #if (ASF_PPI_FLAG_SEQUENCE_FIELD_IS_DWORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_SEQUENCE_FIELD_SIZE)) # define ASF_PPI_SEQUENCE_FIELD_SIZE 4 #endif #ifndef ASF_PPI_SEQUENCE_FIELD_SIZE # define ASF_PPI_SEQUENCE_FIELD_SIZE 0 #endif #if (ASF_PPI_FLAG_PACKET_LENGTH_FIELD_IS_BYTE == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PACKET_LENGTH_FIELD_SIZE)) # define ASF_PPI_PACKET_LENGTH_FIELD_SIZE 1 #endif #if (ASF_PPI_FLAG_PACKET_LENGTH_FIELD_IS_WORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PACKET_LENGTH_FIELD_SIZE)) # define ASF_PPI_PACKET_LENGTH_FIELD_SIZE 2 #endif #if (ASF_PPI_FLAG_PACKET_LENGTH_FIELD_IS_DWORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PACKET_LENGTH_FIELD_SIZE)) # define ASF_PPI_PACKET_LENGTH_FIELD_SIZE 4 #endif #ifndef ASF_PPI_PACKET_LENGTH_FIELD_SIZE # define ASF_PPI_PACKET_LENGTH_FIELD_SIZE 0 #endif #if (ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_BYTE == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PADDING_LENGTH_FIELD_SIZE)) # define ASF_PPI_PADDING_LENGTH_FIELD_SIZE 1 #endif #if (ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_WORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PADDING_LENGTH_FIELD_SIZE)) # define ASF_PPI_PADDING_LENGTH_FIELD_SIZE 2 #endif #if (ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_DWORD == (ASF_PPI_LENGTH_TYPE_FLAGS & ASF_PPI_MASK_PADDING_LENGTH_FIELD_SIZE)) # define ASF_PPI_PADDING_LENGTH_FIELD_SIZE 4 #endif #ifndef ASF_PPI_PADDING_LENGTH_FIELD_SIZE # define ASF_PPI_PADDING_LENGTH_FIELD_SIZE 0 #endif #if (ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_BYTE == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_REPLICATED_DATA_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE 1 #endif #if (ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_WORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_REPLICATED_DATA_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE 2 #endif #if (ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_IS_DWORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_REPLICATED_DATA_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE 4 #endif #ifndef ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE # define ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE 0 #endif #if (ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_BYTE == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE 1 #endif #if (ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_WORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE 2 #endif #if (ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_IS_DWORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE 4 #endif #ifndef ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE # define ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE 0 #endif #if (ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_BYTE == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE 1 #endif #if (ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_WORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE 2 #endif #if (ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_IS_DWORD == (ASF_PPI_PROPERTY_FLAGS & ASF_PL_MASK_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE 4 #endif #ifndef ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE # define ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE 0 #endif #if (ASF_PL_FLAG_PAYLOAD_LENGTH_FIELD_IS_BYTE == (ASF_PAYLOAD_FLAGS & ASF_PL_MASK_PAYLOAD_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_LENGTH_FIELD_SIZE 1 #endif #if (ASF_PL_FLAG_PAYLOAD_LENGTH_FIELD_IS_WORD == (ASF_PAYLOAD_FLAGS & ASF_PL_MASK_PAYLOAD_LENGTH_FIELD_SIZE)) # define ASF_PAYLOAD_LENGTH_FIELD_SIZE 2 #endif #ifndef ASF_PAYLOAD_LENGTH_FIELD_SIZE # define ASF_PAYLOAD_LENGTH_FIELD_SIZE 0 #endif #define PACKET_HEADER_MIN_SIZE (\ ASF_PACKET_ERROR_CORRECTION_FLAGS_FIELD_SIZE + \ ASF_PACKET_ERROR_CORRECTION_DATA_SIZE + \ 1 + /*Length Type Flags*/ \ 1 + /*Property Flags*/ \ ASF_PPI_PACKET_LENGTH_FIELD_SIZE + \ ASF_PPI_SEQUENCE_FIELD_SIZE + \ ASF_PPI_PADDING_LENGTH_FIELD_SIZE + \ 4 + /*Send Time Field*/ \ 2 /*Duration Field*/ \ ) // Replicated Data shall be at least 8 bytes long. #define ASF_PAYLOAD_REPLICATED_DATA_LENGTH 0x08 #define PAYLOAD_HEADER_SIZE_SINGLE_PAYLOAD (\ 1 + /*Stream Number*/ \ ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE + \ ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE + \ ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE + \ ASF_PAYLOAD_REPLICATED_DATA_LENGTH \ ) #define PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS (\ 1 + /*Stream Number*/ \ ASF_PAYLOAD_MEDIA_OBJECT_NUMBER_FIELD_SIZE + \ ASF_PAYLOAD_OFFSET_INTO_MEDIA_OBJECT_FIELD_SIZE + \ ASF_PAYLOAD_REPLICATED_DATA_LENGTH_FIELD_SIZE + \ ASF_PAYLOAD_REPLICATED_DATA_LENGTH + \ ASF_PAYLOAD_LENGTH_FIELD_SIZE \ ) #define SINGLE_PAYLOAD_DATA_LENGTH (\ PACKET_SIZE - \ PACKET_HEADER_MIN_SIZE - \ PAYLOAD_HEADER_SIZE_SINGLE_PAYLOAD \ ) #define MULTI_PAYLOAD_CONSTANT (\ PACKET_SIZE - \ PACKET_HEADER_MIN_SIZE - \ 1 - /*Payload Flags*/ \ 2*PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS \ ) static const AVCodecTag codec_asf_bmp_tags[] = { { CODEC_ID_MPEG4, MKTAG('M', 'P', '4', 'S') }, { CODEC_ID_MPEG4, MKTAG('M', '4', 'S', '2') }, { CODEC_ID_MSMPEG4V3, MKTAG('M', 'P', '4', '3') }, { CODEC_ID_NONE, 0 }, }; #define PREROLL_TIME 3100 static void put_guid(ByteIOContext *s, const ff_asf_guid *g) { assert(sizeof(*g) == 16); put_buffer(s, *g, sizeof(*g)); } static void put_str16(ByteIOContext *s, const char *tag) { int len; uint8_t *pb; ByteIOContext *dyn_buf; if (url_open_dyn_buf(&dyn_buf) < 0) return; ff_put_str16_nolen(dyn_buf, tag); len = url_close_dyn_buf(dyn_buf, &pb); put_le16(s, len); put_buffer(s, pb, len); av_freep(&pb); } static int64_t put_header(ByteIOContext *pb, const ff_asf_guid *g) { int64_t pos; pos = url_ftell(pb); put_guid(pb, g); put_le64(pb, 24); return pos; } /* update header size */ static void end_header(ByteIOContext *pb, int64_t pos) { int64_t pos1; pos1 = url_ftell(pb); url_fseek(pb, pos + 16, SEEK_SET); put_le64(pb, pos1 - pos); url_fseek(pb, pos1, SEEK_SET); } /* write an asf chunk (only used in streaming case) */ static void put_chunk(AVFormatContext *s, int type, int payload_length, int flags) { ASFContext *asf = s->priv_data; ByteIOContext *pb = s->pb; int length; length = payload_length + 8; put_le16(pb, type); put_le16(pb, length); //size put_le32(pb, asf->seqno);//sequence number put_le16(pb, flags); /* unknown bytes */ put_le16(pb, length); //size_confirm asf->seqno++; } /* convert from unix to windows time */ static int64_t unix_to_file_time(int ti) { int64_t t; t = ti * INT64_C(10000000); t += INT64_C(116444736000000000); return t; } /* write the header (used two times if non streamed) */ static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data_chunk_size) { ASFContext *asf = s->priv_data; ByteIOContext *pb = s->pb; AVMetadataTag *tags[5]; int header_size, n, extra_size, extra_size2, wav_extra_size, file_time; int has_title; int metadata_count; AVCodecContext *enc; int64_t header_offset, cur_pos, hpos; int bit_rate; int64_t duration; tags[0] = av_metadata_get(s->metadata, "title" , NULL, 0); tags[1] = av_metadata_get(s->metadata, "author" , NULL, 0); tags[2] = av_metadata_get(s->metadata, "copyright", NULL, 0); tags[3] = av_metadata_get(s->metadata, "comment" , NULL, 0); tags[4] = av_metadata_get(s->metadata, "rating" , NULL, 0); duration = asf->duration + PREROLL_TIME * 10000; has_title = tags[0] || tags[1] || tags[2] || tags[3] || tags[4]; metadata_count = s->metadata ? s->metadata->count : 0; bit_rate = 0; for(n=0;n<s->nb_streams;n++) { enc = s->streams[n]->codec; av_set_pts_info(s->streams[n], 32, 1, 1000); /* 32 bit pts in ms */ bit_rate += enc->bit_rate; } if (asf->is_streamed) { put_chunk(s, 0x4824, 0, 0xc00); /* start of stream (length will be patched later) */ } put_guid(pb, &ff_asf_header); put_le64(pb, -1); /* header length, will be patched after */ put_le32(pb, 3 + has_title + !!metadata_count + s->nb_streams); /* number of chunks in header */ put_byte(pb, 1); /* ??? */ put_byte(pb, 2); /* ??? */ /* file header */ header_offset = url_ftell(pb); hpos = put_header(pb, &ff_asf_file_header); put_guid(pb, &ff_asf_my_guid); put_le64(pb, file_size); file_time = 0; put_le64(pb, unix_to_file_time(file_time)); put_le64(pb, asf->nb_packets); /* number of packets */ put_le64(pb, duration); /* end time stamp (in 100ns units) */ put_le64(pb, asf->duration); /* duration (in 100ns units) */ put_le64(pb, PREROLL_TIME); /* start time stamp */ put_le32(pb, (asf->is_streamed || url_is_streamed(pb)) ? 3 : 2); /* ??? */ put_le32(pb, s->packet_size); /* packet size */ put_le32(pb, s->packet_size); /* packet size */ put_le32(pb, bit_rate); /* Nominal data rate in bps */ end_header(pb, hpos); /* unknown headers */ hpos = put_header(pb, &ff_asf_head1_guid); put_guid(pb, &ff_asf_head2_guid); put_le32(pb, 6); put_le16(pb, 0); end_header(pb, hpos); /* title and other infos */ if (has_title) { int len; uint8_t *buf; ByteIOContext *dyn_buf; if (url_open_dyn_buf(&dyn_buf) < 0) return AVERROR(ENOMEM); hpos = put_header(pb, &ff_asf_comment_header); for (n = 0; n < FF_ARRAY_ELEMS(tags); n++) { len = tags[n] ? ff_put_str16_nolen(dyn_buf, tags[n]->value) : 0; put_le16(pb, len); } len = url_close_dyn_buf(dyn_buf, &buf); put_buffer(pb, buf, len); av_freep(&buf); end_header(pb, hpos); } if (metadata_count) { AVMetadataTag *tag = NULL; hpos = put_header(pb, &ff_asf_extended_content_header); put_le16(pb, metadata_count); while ((tag = av_metadata_get(s->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX))) { put_str16(pb, tag->key); put_le16(pb, 0); put_str16(pb, tag->value); } end_header(pb, hpos); } /* stream headers */ for(n=0;n<s->nb_streams;n++) { int64_t es_pos; // ASFStream *stream = &asf->streams[n]; enc = s->streams[n]->codec; asf->streams[n].num = n + 1; asf->streams[n].seq = 0; switch(enc->codec_type) { case AVMEDIA_TYPE_AUDIO: wav_extra_size = 0; extra_size = 18 + wav_extra_size; extra_size2 = 8; break; default: case AVMEDIA_TYPE_VIDEO: wav_extra_size = enc->extradata_size; extra_size = 0x33 + wav_extra_size; extra_size2 = 0; break; } hpos = put_header(pb, &ff_asf_stream_header); if (enc->codec_type == AVMEDIA_TYPE_AUDIO) { put_guid(pb, &ff_asf_audio_stream); put_guid(pb, &ff_asf_audio_conceal_spread); } else { put_guid(pb, &ff_asf_video_stream); put_guid(pb, &ff_asf_video_conceal_none); } put_le64(pb, 0); /* ??? */ es_pos = url_ftell(pb); put_le32(pb, extra_size); /* wav header len */ put_le32(pb, extra_size2); /* additional data len */ put_le16(pb, n + 1); /* stream number */ put_le32(pb, 0); /* ??? */ if (enc->codec_type == AVMEDIA_TYPE_AUDIO) { /* WAVEFORMATEX header */ int wavsize = ff_put_wav_header(pb, enc); if ((enc->codec_id != CODEC_ID_MP3) && (enc->codec_id != CODEC_ID_MP2) && (enc->codec_id != CODEC_ID_ADPCM_IMA_WAV) && (enc->extradata_size==0)) { wavsize += 2; put_le16(pb, 0); } if (wavsize < 0) return -1; if (wavsize != extra_size) { cur_pos = url_ftell(pb); url_fseek(pb, es_pos, SEEK_SET); put_le32(pb, wavsize); /* wav header len */ url_fseek(pb, cur_pos, SEEK_SET); } /* ERROR Correction */ put_byte(pb, 0x01); if(enc->codec_id == CODEC_ID_ADPCM_G726 || !enc->block_align){ put_le16(pb, 0x0190); put_le16(pb, 0x0190); }else{ put_le16(pb, enc->block_align); put_le16(pb, enc->block_align); } put_le16(pb, 0x01); put_byte(pb, 0x00); } else { put_le32(pb, enc->width); put_le32(pb, enc->height); put_byte(pb, 2); /* ??? */ put_le16(pb, 40 + enc->extradata_size); /* size */ /* BITMAPINFOHEADER header */ ff_put_bmp_header(pb, enc, ff_codec_bmp_tags, 1); } end_header(pb, hpos); } /* media comments */ hpos = put_header(pb, &ff_asf_codec_comment_header); put_guid(pb, &ff_asf_codec_comment1_header); put_le32(pb, s->nb_streams); for(n=0;n<s->nb_streams;n++) { AVCodec *p; const char *desc; int len; uint8_t *buf; ByteIOContext *dyn_buf; enc = s->streams[n]->codec; p = avcodec_find_encoder(enc->codec_id); if(enc->codec_type == AVMEDIA_TYPE_AUDIO) put_le16(pb, 2); else if(enc->codec_type == AVMEDIA_TYPE_VIDEO) put_le16(pb, 1); else put_le16(pb, -1); if(enc->codec_id == CODEC_ID_WMAV2) desc = "Windows Media Audio V8"; else desc = p ? p->name : enc->codec_name; if ( url_open_dyn_buf(&dyn_buf) < 0) return AVERROR(ENOMEM); ff_put_str16_nolen(dyn_buf, desc); len = url_close_dyn_buf(dyn_buf, &buf); put_le16(pb, len / 2); // "number of characters" = length in bytes / 2 put_buffer(pb, buf, len); av_freep(&buf); put_le16(pb, 0); /* no parameters */ /* id */ if (enc->codec_type == AVMEDIA_TYPE_AUDIO) { put_le16(pb, 2); put_le16(pb, enc->codec_tag); } else { put_le16(pb, 4); put_le32(pb, enc->codec_tag); } if(!enc->codec_tag) return -1; } end_header(pb, hpos); /* patch the header size fields */ cur_pos = url_ftell(pb); header_size = cur_pos - header_offset; if (asf->is_streamed) { header_size += 8 + 30 + 50; url_fseek(pb, header_offset - 10 - 30, SEEK_SET); put_le16(pb, header_size); url_fseek(pb, header_offset - 2 - 30, SEEK_SET); put_le16(pb, header_size); header_size -= 8 + 30 + 50; } header_size += 24 + 6; url_fseek(pb, header_offset - 14, SEEK_SET); put_le64(pb, header_size); url_fseek(pb, cur_pos, SEEK_SET); /* movie chunk, followed by packets of packet_size */ asf->data_offset = cur_pos; put_guid(pb, &ff_asf_data_header); put_le64(pb, data_chunk_size); put_guid(pb, &ff_asf_my_guid); put_le64(pb, asf->nb_packets); /* nb packets */ put_byte(pb, 1); /* ??? */ put_byte(pb, 1); /* ??? */ return 0; } static int asf_write_header(AVFormatContext *s) { ASFContext *asf = s->priv_data; s->packet_size = PACKET_SIZE; asf->nb_packets = 0; asf->last_indexed_pts = 0; asf->index_ptr = av_malloc( sizeof(ASFIndex) * ASF_INDEX_BLOCK ); asf->nb_index_memory_alloc = ASF_INDEX_BLOCK; asf->nb_index_count = 0; asf->maximum_packet = 0; /* the data-chunk-size has to be 50, which is data_size - asf->data_offset * at the moment this function is done. It is needed to use asf as * streamable format. */ if (asf_write_header1(s, 0, 50) < 0) { //av_free(asf); return -1; } put_flush_packet(s->pb); asf->packet_nb_payloads = 0; asf->packet_timestamp_start = -1; asf->packet_timestamp_end = -1; init_put_byte(&asf->pb, asf->packet_buf, s->packet_size, 1, NULL, NULL, NULL, NULL); return 0; } static int asf_write_stream_header(AVFormatContext *s) { ASFContext *asf = s->priv_data; asf->is_streamed = 1; return asf_write_header(s); } static int put_payload_parsing_info( AVFormatContext *s, unsigned int sendtime, unsigned int duration, int nb_payloads, int padsize ) { ASFContext *asf = s->priv_data; ByteIOContext *pb = s->pb; int ppi_size, i; int64_t start= url_ftell(pb); int iLengthTypeFlags = ASF_PPI_LENGTH_TYPE_FLAGS; padsize -= PACKET_HEADER_MIN_SIZE; if(asf->multi_payloads_present) padsize--; assert(padsize>=0); put_byte(pb, ASF_PACKET_ERROR_CORRECTION_FLAGS); for (i = 0; i < ASF_PACKET_ERROR_CORRECTION_DATA_SIZE; i++){ put_byte(pb, 0x0); } if (asf->multi_payloads_present) iLengthTypeFlags |= ASF_PPI_FLAG_MULTIPLE_PAYLOADS_PRESENT; if (padsize > 0) { if (padsize < 256) iLengthTypeFlags |= ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_BYTE; else iLengthTypeFlags |= ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_WORD; } put_byte(pb, iLengthTypeFlags); put_byte(pb, ASF_PPI_PROPERTY_FLAGS); if (iLengthTypeFlags & ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_WORD) put_le16(pb, padsize - 2); if (iLengthTypeFlags & ASF_PPI_FLAG_PADDING_LENGTH_FIELD_IS_BYTE) put_byte(pb, padsize - 1); put_le32(pb, sendtime); put_le16(pb, duration); if (asf->multi_payloads_present) put_byte(pb, nb_payloads | ASF_PAYLOAD_FLAGS); ppi_size = url_ftell(pb) - start; return ppi_size; } static void flush_packet(AVFormatContext *s) { ASFContext *asf = s->priv_data; int packet_hdr_size, packet_filled_size; assert(asf->packet_timestamp_end >= asf->packet_timestamp_start); if (asf->is_streamed) { put_chunk(s, 0x4424, s->packet_size, 0); } packet_hdr_size = put_payload_parsing_info( s, asf->packet_timestamp_start, asf->packet_timestamp_end - asf->packet_timestamp_start, asf->packet_nb_payloads, asf->packet_size_left ); packet_filled_size = PACKET_SIZE - asf->packet_size_left; assert(packet_hdr_size <= asf->packet_size_left); memset(asf->packet_buf + packet_filled_size, 0, asf->packet_size_left); put_buffer(s->pb, asf->packet_buf, s->packet_size - packet_hdr_size); put_flush_packet(s->pb); asf->nb_packets++; asf->packet_nb_payloads = 0; asf->packet_timestamp_start = -1; asf->packet_timestamp_end = -1; init_put_byte(&asf->pb, asf->packet_buf, s->packet_size, 1, NULL, NULL, NULL, NULL); } static void put_payload_header( AVFormatContext *s, ASFStream *stream, int presentation_time, int m_obj_size, int m_obj_offset, int payload_len, int flags ) { ASFContext *asf = s->priv_data; ByteIOContext *pb = &asf->pb; int val; val = stream->num; if (flags & AV_PKT_FLAG_KEY) val |= ASF_PL_FLAG_KEY_FRAME; put_byte(pb, val); put_byte(pb, stream->seq); //Media object number put_le32(pb, m_obj_offset); //Offset Into Media Object // Replicated Data shall be at least 8 bytes long. // The first 4 bytes of data shall contain the // Size of the Media Object that the payload belongs to. // The next 4 bytes of data shall contain the // Presentation Time for the media object that the payload belongs to. put_byte(pb, ASF_PAYLOAD_REPLICATED_DATA_LENGTH); put_le32(pb, m_obj_size); //Replicated Data - Media Object Size put_le32(pb, presentation_time);//Replicated Data - Presentation Time if (asf->multi_payloads_present){ put_le16(pb, payload_len); //payload length } } static void put_frame( AVFormatContext *s, ASFStream *stream, AVStream *avst, int timestamp, const uint8_t *buf, int m_obj_size, int flags ) { ASFContext *asf = s->priv_data; int m_obj_offset, payload_len, frag_len1; m_obj_offset = 0; while (m_obj_offset < m_obj_size) { payload_len = m_obj_size - m_obj_offset; if (asf->packet_timestamp_start == -1) { asf->multi_payloads_present = (payload_len < MULTI_PAYLOAD_CONSTANT); asf->packet_size_left = PACKET_SIZE; if (asf->multi_payloads_present){ frag_len1 = MULTI_PAYLOAD_CONSTANT - 1; } else { frag_len1 = SINGLE_PAYLOAD_DATA_LENGTH; } asf->packet_timestamp_start = timestamp; } else { // multi payloads frag_len1 = asf->packet_size_left - PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS - PACKET_HEADER_MIN_SIZE - 1; if(frag_len1 < payload_len && avst->codec->codec_type == AVMEDIA_TYPE_AUDIO){ flush_packet(s); continue; } } if (frag_len1 > 0) { if (payload_len > frag_len1) payload_len = frag_len1; else if (payload_len == (frag_len1 - 1)) payload_len = frag_len1 - 2; //additional byte need to put padding length put_payload_header(s, stream, timestamp+PREROLL_TIME, m_obj_size, m_obj_offset, payload_len, flags); put_buffer(&asf->pb, buf, payload_len); if (asf->multi_payloads_present) asf->packet_size_left -= (payload_len + PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS); else asf->packet_size_left -= (payload_len + PAYLOAD_HEADER_SIZE_SINGLE_PAYLOAD); asf->packet_timestamp_end = timestamp; asf->packet_nb_payloads++; } else { payload_len = 0; } m_obj_offset += payload_len; buf += payload_len; if (!asf->multi_payloads_present) flush_packet(s); else if (asf->packet_size_left <= (PAYLOAD_HEADER_SIZE_MULTIPLE_PAYLOADS + PACKET_HEADER_MIN_SIZE + 1)) flush_packet(s); } stream->seq++; } static int asf_write_packet(AVFormatContext *s, AVPacket *pkt) { ASFContext *asf = s->priv_data; ASFStream *stream; int64_t duration; AVCodecContext *codec; int64_t packet_st,pts; int start_sec,i; int flags= pkt->flags; codec = s->streams[pkt->stream_index]->codec; stream = &asf->streams[pkt->stream_index]; if(codec->codec_type == AVMEDIA_TYPE_AUDIO) flags &= ~AV_PKT_FLAG_KEY; pts = (pkt->pts != AV_NOPTS_VALUE) ? pkt->pts : pkt->dts; assert(pts != AV_NOPTS_VALUE); duration = pts * 10000; asf->duration= FFMAX(asf->duration, duration + pkt->duration * 10000); packet_st = asf->nb_packets; put_frame(s, stream, s->streams[pkt->stream_index], pkt->dts, pkt->data, pkt->size, flags); /* check index */ if ((!asf->is_streamed) && (flags & AV_PKT_FLAG_KEY)) { start_sec = (int)(duration / INT64_C(10000000)); if (start_sec != (int)(asf->last_indexed_pts / INT64_C(10000000))) { for(i=asf->nb_index_count;i<start_sec;i++) { if (i>=asf->nb_index_memory_alloc) { asf->nb_index_memory_alloc += ASF_INDEX_BLOCK; asf->index_ptr = (ASFIndex*)av_realloc( asf->index_ptr, sizeof(ASFIndex) * asf->nb_index_memory_alloc ); } // store asf->index_ptr[i].packet_number = (uint32_t)packet_st; asf->index_ptr[i].packet_count = (uint16_t)(asf->nb_packets-packet_st); asf->maximum_packet = FFMAX(asf->maximum_packet, (uint16_t)(asf->nb_packets-packet_st)); } asf->nb_index_count = start_sec; asf->last_indexed_pts = duration; } } return 0; } // static int asf_write_index(AVFormatContext *s, ASFIndex *index, uint16_t max, uint32_t count) { ByteIOContext *pb = s->pb; int i; put_guid(pb, &ff_asf_simple_index_header); put_le64(pb, 24 + 16 + 8 + 4 + 4 + (4 + 2)*count); put_guid(pb, &ff_asf_my_guid); put_le64(pb, ASF_INDEXED_INTERVAL); put_le32(pb, max); put_le32(pb, count); for(i=0; i<count; i++) { put_le32(pb, index[i].packet_number); put_le16(pb, index[i].packet_count); } return 0; } static int asf_write_trailer(AVFormatContext *s) { ASFContext *asf = s->priv_data; int64_t file_size,data_size; /* flush the current packet */ if (asf->pb.buf_ptr > asf->pb.buffer) flush_packet(s); /* write index */ data_size = url_ftell(s->pb); if ((!asf->is_streamed) && (asf->nb_index_count != 0)) { asf_write_index(s, asf->index_ptr, asf->maximum_packet, asf->nb_index_count); } put_flush_packet(s->pb); if (asf->is_streamed || url_is_streamed(s->pb)) { put_chunk(s, 0x4524, 0, 0); /* end of stream */ } else { /* rewrite an updated header */ file_size = url_ftell(s->pb); url_fseek(s->pb, 0, SEEK_SET); asf_write_header1(s, file_size, data_size - asf->data_offset); } put_flush_packet(s->pb); av_free(asf->index_ptr); return 0; } #if CONFIG_ASF_MUXER AVOutputFormat asf_muxer = { "asf", NULL_IF_CONFIG_SMALL("ASF format"), "video/x-ms-asf", "asf,wmv,wma", sizeof(ASFContext), #if CONFIG_LIBMP3LAME CODEC_ID_MP3, #else CODEC_ID_MP2, #endif CODEC_ID_MSMPEG4V3, asf_write_header, asf_write_packet, asf_write_trailer, .flags = AVFMT_GLOBALHEADER, .codec_tag= (const AVCodecTag* const []){codec_asf_bmp_tags, ff_codec_bmp_tags, ff_codec_wav_tags, 0}, .metadata_conv = ff_asf_metadata_conv, }; #endif #if CONFIG_ASF_STREAM_MUXER AVOutputFormat asf_stream_muxer = { "asf_stream", NULL_IF_CONFIG_SMALL("ASF format"), "video/x-ms-asf", "asf,wmv,wma", sizeof(ASFContext), #if CONFIG_LIBMP3LAME CODEC_ID_MP3, #else CODEC_ID_MP2, #endif CODEC_ID_MSMPEG4V3, asf_write_stream_header, asf_write_packet, asf_write_trailer, .flags = AVFMT_GLOBALHEADER, .codec_tag= (const AVCodecTag* const []){codec_asf_bmp_tags, ff_codec_bmp_tags, ff_codec_wav_tags, 0}, .metadata_conv = ff_asf_metadata_conv, }; #endif //CONFIG_ASF_STREAM_MUXER
123linslouis-android-video-cutter
jni/libavformat/asfenc.c
C
asf20
30,223
/* * TCP protocol * Copyright (c) 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avformat.h" #include <unistd.h> #include "internal.h" #include "network.h" #include "os_support.h" #if HAVE_SYS_SELECT_H #include <sys/select.h> #endif #include <sys/time.h> typedef struct TCPContext { int fd; } TCPContext; /* return non zero if error */ static int tcp_open(URLContext *h, const char *uri, int flags) { struct addrinfo hints, *ai, *cur_ai; int port, fd = -1; TCPContext *s = NULL; fd_set wfds; int fd_max, ret; struct timeval tv; socklen_t optlen; char hostname[1024],proto[1024],path[1024]; char portstr[10]; ff_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port, path, sizeof(path), uri); if (strcmp(proto,"tcp") || port <= 0 || port >= 65536) return AVERROR(EINVAL); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; snprintf(portstr, sizeof(portstr), "%d", port); if (getaddrinfo(hostname, portstr, &hints, &ai)) return AVERROR(EIO); cur_ai = ai; restart: fd = socket(cur_ai->ai_family, cur_ai->ai_socktype, cur_ai->ai_protocol); if (fd < 0) goto fail; ff_socket_nonblock(fd, 1); redo: ret = connect(fd, cur_ai->ai_addr, cur_ai->ai_addrlen); if (ret < 0) { if (ff_neterrno() == FF_NETERROR(EINTR)) goto redo; if (ff_neterrno() != FF_NETERROR(EINPROGRESS) && ff_neterrno() != FF_NETERROR(EAGAIN)) goto fail; /* wait until we are connected or until abort */ for(;;) { if (url_interrupt_cb()) { ret = AVERROR(EINTR); goto fail1; } fd_max = fd; FD_ZERO(&wfds); FD_SET(fd, &wfds); tv.tv_sec = 0; tv.tv_usec = 100 * 1000; ret = select(fd_max + 1, NULL, &wfds, NULL, &tv); if (ret > 0 && FD_ISSET(fd, &wfds)) break; } /* test error */ optlen = sizeof(ret); getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen); if (ret != 0) goto fail; } s = av_malloc(sizeof(TCPContext)); if (!s) { freeaddrinfo(ai); return AVERROR(ENOMEM); } h->priv_data = s; h->is_streamed = 1; s->fd = fd; freeaddrinfo(ai); return 0; fail: if (cur_ai->ai_next) { /* Retry with the next sockaddr */ cur_ai = cur_ai->ai_next; if (fd >= 0) closesocket(fd); goto restart; } ret = AVERROR(EIO); fail1: if (fd >= 0) closesocket(fd); freeaddrinfo(ai); return ret; } static int tcp_read(URLContext *h, uint8_t *buf, int size) { TCPContext *s = h->priv_data; int len, fd_max, ret; fd_set rfds; struct timeval tv; for (;;) { if (url_interrupt_cb()) return AVERROR(EINTR); fd_max = s->fd; FD_ZERO(&rfds); FD_SET(s->fd, &rfds); tv.tv_sec = 0; tv.tv_usec = 100 * 1000; ret = select(fd_max + 1, &rfds, NULL, NULL, &tv); if (ret > 0 && FD_ISSET(s->fd, &rfds)) { len = recv(s->fd, buf, size, 0); if (len < 0) { if (ff_neterrno() != FF_NETERROR(EINTR) && ff_neterrno() != FF_NETERROR(EAGAIN)) return AVERROR(ff_neterrno()); } else return len; } else if (ret < 0) { if (ff_neterrno() == FF_NETERROR(EINTR)) continue; return -1; } } } static int tcp_write(URLContext *h, uint8_t *buf, int size) { TCPContext *s = h->priv_data; int ret, size1, fd_max, len; fd_set wfds; struct timeval tv; size1 = size; while (size > 0) { if (url_interrupt_cb()) return AVERROR(EINTR); fd_max = s->fd; FD_ZERO(&wfds); FD_SET(s->fd, &wfds); tv.tv_sec = 0; tv.tv_usec = 100 * 1000; ret = select(fd_max + 1, NULL, &wfds, NULL, &tv); if (ret > 0 && FD_ISSET(s->fd, &wfds)) { len = send(s->fd, buf, size, 0); if (len < 0) { if (ff_neterrno() != FF_NETERROR(EINTR) && ff_neterrno() != FF_NETERROR(EAGAIN)) return AVERROR(ff_neterrno()); continue; } size -= len; buf += len; } else if (ret < 0) { if (ff_neterrno() == FF_NETERROR(EINTR)) continue; return -1; } } return size1 - size; } static int tcp_close(URLContext *h) { TCPContext *s = h->priv_data; closesocket(s->fd); av_free(s); return 0; } static int tcp_get_file_handle(URLContext *h) { TCPContext *s = h->priv_data; return s->fd; } URLProtocol tcp_protocol = { "tcp", tcp_open, tcp_read, tcp_write, NULL, /* seek */ tcp_close, .url_get_file_handle = tcp_get_file_handle, };
123linslouis-android-video-cutter
jni/libavformat/tcp.c
C
asf20
5,820
/* * Tiertex Limited SEQ File Demuxer * Copyright (c) 2006 Gregory Montoir (cyx@users.sourceforge.net) * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Tiertex Limited SEQ file demuxer */ #include "avformat.h" #define SEQ_FRAME_SIZE 6144 #define SEQ_FRAME_W 256 #define SEQ_FRAME_H 128 #define SEQ_NUM_FRAME_BUFFERS 30 #define SEQ_AUDIO_BUFFER_SIZE 882 #define SEQ_SAMPLE_RATE 22050 #define SEQ_FRAME_RATE 25 typedef struct TiertexSeqFrameBuffer { int fill_size; int data_size; unsigned char *data; } TiertexSeqFrameBuffer; typedef struct SeqDemuxContext { int audio_stream_index; int video_stream_index; int current_frame_pts; int current_frame_offs; TiertexSeqFrameBuffer frame_buffers[SEQ_NUM_FRAME_BUFFERS]; int frame_buffers_count; unsigned int current_audio_data_size; unsigned int current_audio_data_offs; unsigned int current_pal_data_size; unsigned int current_pal_data_offs; unsigned int current_video_data_size; unsigned char *current_video_data_ptr; int audio_buffer_full; } SeqDemuxContext; static int seq_probe(AVProbeData *p) { int i; if (p->buf_size < 258) return 0; /* there's no real header in a .seq file, the only thing they have in common */ /* is the first 256 bytes of the file which are always filled with 0 */ for (i = 0; i < 256; i++) if (p->buf[i]) return 0; if(p->buf[256]==0 && p->buf[257]==0) return 0; /* only one fourth of the score since the previous check is too naive */ return AVPROBE_SCORE_MAX / 4; } static int seq_init_frame_buffers(SeqDemuxContext *seq, ByteIOContext *pb) { int i, sz; TiertexSeqFrameBuffer *seq_buffer; url_fseek(pb, 256, SEEK_SET); for (i = 0; i < SEQ_NUM_FRAME_BUFFERS; i++) { sz = get_le16(pb); if (sz == 0) break; else { seq_buffer = &seq->frame_buffers[i]; seq_buffer->fill_size = 0; seq_buffer->data_size = sz; seq_buffer->data = av_malloc(sz); if (!seq_buffer->data) return AVERROR(ENOMEM); } } seq->frame_buffers_count = i; return 0; } static int seq_fill_buffer(SeqDemuxContext *seq, ByteIOContext *pb, int buffer_num, unsigned int data_offs, int data_size) { TiertexSeqFrameBuffer *seq_buffer; if (buffer_num >= SEQ_NUM_FRAME_BUFFERS) return AVERROR_INVALIDDATA; seq_buffer = &seq->frame_buffers[buffer_num]; if (seq_buffer->fill_size + data_size > seq_buffer->data_size || data_size <= 0) return AVERROR_INVALIDDATA; url_fseek(pb, seq->current_frame_offs + data_offs, SEEK_SET); if (get_buffer(pb, seq_buffer->data + seq_buffer->fill_size, data_size) != data_size) return AVERROR(EIO); seq_buffer->fill_size += data_size; return 0; } static int seq_parse_frame_data(SeqDemuxContext *seq, ByteIOContext *pb) { unsigned int offset_table[4], buffer_num[4]; TiertexSeqFrameBuffer *seq_buffer; int i, e, err; seq->current_frame_offs += SEQ_FRAME_SIZE; url_fseek(pb, seq->current_frame_offs, SEEK_SET); /* sound data */ seq->current_audio_data_offs = get_le16(pb); if (seq->current_audio_data_offs) { seq->current_audio_data_size = SEQ_AUDIO_BUFFER_SIZE * 2; } else { seq->current_audio_data_size = 0; } /* palette data */ seq->current_pal_data_offs = get_le16(pb); if (seq->current_pal_data_offs) { seq->current_pal_data_size = 768; } else { seq->current_pal_data_size = 0; } /* video data */ for (i = 0; i < 4; i++) buffer_num[i] = get_byte(pb); for (i = 0; i < 4; i++) offset_table[i] = get_le16(pb); for (i = 0; i < 3; i++) { if (offset_table[i]) { for (e = i + 1; e < 3 && offset_table[e] == 0; e++); err = seq_fill_buffer(seq, pb, buffer_num[1 + i], offset_table[i], offset_table[e] - offset_table[i]); if (err) return err; } } if (buffer_num[0] != 255) { if (buffer_num[0] >= SEQ_NUM_FRAME_BUFFERS) return AVERROR_INVALIDDATA; seq_buffer = &seq->frame_buffers[buffer_num[0]]; seq->current_video_data_size = seq_buffer->fill_size; seq->current_video_data_ptr = seq_buffer->data; seq_buffer->fill_size = 0; } else { seq->current_video_data_size = 0; seq->current_video_data_ptr = 0; } return 0; } static int seq_read_header(AVFormatContext *s, AVFormatParameters *ap) { int i, rc; SeqDemuxContext *seq = s->priv_data; ByteIOContext *pb = s->pb; AVStream *st; /* init internal buffers */ rc = seq_init_frame_buffers(seq, pb); if (rc) return rc; seq->current_frame_offs = 0; /* preload (no audio data, just buffer operations related data) */ for (i = 1; i <= 100; i++) { rc = seq_parse_frame_data(seq, pb); if (rc) return rc; } seq->current_frame_pts = 0; seq->audio_buffer_full = 0; /* initialize the video decoder stream */ st = av_new_stream(s, 0); if (!st) return AVERROR(ENOMEM); av_set_pts_info(st, 32, 1, SEQ_FRAME_RATE); seq->video_stream_index = st->index; st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = CODEC_ID_TIERTEXSEQVIDEO; st->codec->codec_tag = 0; /* no fourcc */ st->codec->width = SEQ_FRAME_W; st->codec->height = SEQ_FRAME_H; /* initialize the audio decoder stream */ st = av_new_stream(s, 0); if (!st) return AVERROR(ENOMEM); av_set_pts_info(st, 32, 1, SEQ_SAMPLE_RATE); seq->audio_stream_index = st->index; st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_id = CODEC_ID_PCM_S16BE; st->codec->codec_tag = 0; /* no tag */ st->codec->channels = 1; st->codec->sample_rate = SEQ_SAMPLE_RATE; st->codec->bits_per_coded_sample = 16; st->codec->bit_rate = st->codec->sample_rate * st->codec->bits_per_coded_sample * st->codec->channels; st->codec->block_align = st->codec->channels * st->codec->bits_per_coded_sample; return 0; } static int seq_read_packet(AVFormatContext *s, AVPacket *pkt) { int rc; SeqDemuxContext *seq = s->priv_data; ByteIOContext *pb = s->pb; if (!seq->audio_buffer_full) { rc = seq_parse_frame_data(seq, pb); if (rc) return rc; /* video packet */ if (seq->current_pal_data_size + seq->current_video_data_size != 0) { if (av_new_packet(pkt, 1 + seq->current_pal_data_size + seq->current_video_data_size)) return AVERROR(ENOMEM); pkt->data[0] = 0; if (seq->current_pal_data_size) { pkt->data[0] |= 1; url_fseek(pb, seq->current_frame_offs + seq->current_pal_data_offs, SEEK_SET); if (get_buffer(pb, &pkt->data[1], seq->current_pal_data_size) != seq->current_pal_data_size) return AVERROR(EIO); } if (seq->current_video_data_size) { pkt->data[0] |= 2; memcpy(&pkt->data[1 + seq->current_pal_data_size], seq->current_video_data_ptr, seq->current_video_data_size); } pkt->stream_index = seq->video_stream_index; pkt->pts = seq->current_frame_pts; /* sound buffer will be processed on next read_packet() call */ seq->audio_buffer_full = 1; return 0; } } /* audio packet */ if (seq->current_audio_data_offs == 0) /* end of data reached */ return AVERROR(EIO); url_fseek(pb, seq->current_frame_offs + seq->current_audio_data_offs, SEEK_SET); rc = av_get_packet(pb, pkt, seq->current_audio_data_size); if (rc < 0) return rc; pkt->stream_index = seq->audio_stream_index; seq->current_frame_pts++; seq->audio_buffer_full = 0; return 0; } static int seq_read_close(AVFormatContext *s) { int i; SeqDemuxContext *seq = s->priv_data; for (i = 0; i < SEQ_NUM_FRAME_BUFFERS; i++) av_free(seq->frame_buffers[i].data); return 0; } AVInputFormat tiertexseq_demuxer = { "tiertexseq", NULL_IF_CONFIG_SMALL("Tiertex Limited SEQ format"), sizeof(SeqDemuxContext), seq_probe, seq_read_header, seq_read_packet, seq_read_close, };
123linslouis-android-video-cutter
jni/libavformat/tiertexseq.c
C
asf20
9,280
/* * Deluxe Paint Animation demuxer * Copyright (c) 2009 Peter Ross * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Deluxe Paint Animation demuxer */ #include "libavutil/intreadwrite.h" #include "avformat.h" typedef struct { int base_record; unsigned int nb_records; int size; } Page; typedef struct { unsigned int nb_pages; /** total pages in file */ unsigned int nb_records; /** total records in file */ int page_table_offset; #define MAX_PAGES 256 /** Deluxe Paint hardcoded value */ Page pt[MAX_PAGES]; /** page table */ int page; /** current page (or AVERROR_xxx code) */ int record; /** current record (with in page) */ } AnmDemuxContext; #define LPF_TAG MKTAG('L','P','F',' ') #define ANIM_TAG MKTAG('A','N','I','M') static int probe(AVProbeData *p) { /* verify tags and video dimensions */ if (AV_RL32(&p->buf[0]) == LPF_TAG && AV_RL32(&p->buf[16]) == ANIM_TAG && AV_RL16(&p->buf[20]) && AV_RL16(&p->buf[22])) return AVPROBE_SCORE_MAX; return 0; } /** * @return page containing the requested record or AVERROR_XXX */ static int find_record(const AnmDemuxContext *anm, int record) { int i; if (record >= anm->nb_records) return AVERROR_EOF; for (i = 0; i < MAX_PAGES; i++) { const Page *p = &anm->pt[i]; if (p->nb_records > 0 && record >= p->base_record && record < p->base_record + p->nb_records) return i; } return AVERROR_INVALIDDATA; } static int read_header(AVFormatContext *s, AVFormatParameters *ap) { AnmDemuxContext *anm = s->priv_data; ByteIOContext *pb = s->pb; AVStream *st; int i, ret; url_fskip(pb, 4); /* magic number */ if (get_le16(pb) != MAX_PAGES) { av_log_ask_for_sample(s, "max_pages != " AV_STRINGIFY(MAX_PAGES) "\n"); return AVERROR_INVALIDDATA; } anm->nb_pages = get_le16(pb); anm->nb_records = get_le32(pb); url_fskip(pb, 2); /* max records per page */ anm->page_table_offset = get_le16(pb); if (get_le32(pb) != ANIM_TAG) return AVERROR_INVALIDDATA; /* video stream */ st = av_new_stream(s, 0); if (!st) return AVERROR(ENOMEM); st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = CODEC_ID_ANM; st->codec->codec_tag = 0; /* no fourcc */ st->codec->width = get_le16(pb); st->codec->height = get_le16(pb); if (get_byte(pb) != 0) goto invalid; url_fskip(pb, 1); /* frame rate multiplier info */ /* ignore last delta record (used for looping) */ if (get_byte(pb)) /* has_last_delta */ anm->nb_records = FFMAX(anm->nb_records - 1, 0); url_fskip(pb, 1); /* last_delta_valid */ if (get_byte(pb) != 0) goto invalid; if (get_byte(pb) != 1) goto invalid; url_fskip(pb, 1); /* other recs per frame */ if (get_byte(pb) != 1) goto invalid; url_fskip(pb, 32); /* record_types */ st->nb_frames = get_le32(pb); av_set_pts_info(st, 64, 1, get_le16(pb)); url_fskip(pb, 58); /* color cycling and palette data */ st->codec->extradata_size = 16*8 + 4*256; st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE); if (!st->codec->extradata) { ret = AVERROR(ENOMEM); goto close_and_return; } ret = get_buffer(pb, st->codec->extradata, st->codec->extradata_size); if (ret < 0) goto close_and_return; /* read page table */ ret = url_fseek(pb, anm->page_table_offset, SEEK_SET); if (ret < 0) goto close_and_return; for (i = 0; i < MAX_PAGES; i++) { Page *p = &anm->pt[i]; p->base_record = get_le16(pb); p->nb_records = get_le16(pb); p->size = get_le16(pb); } /* find page of first frame */ anm->page = find_record(anm, 0); if (anm->page < 0) { ret = anm->page; goto close_and_return; } anm->record = -1; return 0; invalid: av_log_ask_for_sample(s, NULL); ret = AVERROR_INVALIDDATA; close_and_return: av_close_input_stream(s); return ret; } static int read_packet(AVFormatContext *s, AVPacket *pkt) { AnmDemuxContext *anm = s->priv_data; ByteIOContext *pb = s->pb; Page *p; int tmp, record_size; if (url_feof(s->pb)) return AVERROR(EIO); if (anm->page < 0) return anm->page; repeat: p = &anm->pt[anm->page]; /* parse page header */ if (anm->record < 0) { url_fseek(pb, anm->page_table_offset + MAX_PAGES*6 + (anm->page<<16), SEEK_SET); url_fskip(pb, 8 + 2*p->nb_records); anm->record = 0; } /* if we have fetched all records in this page, then find the next page and repeat */ if (anm->record >= p->nb_records) { anm->page = find_record(anm, p->base_record + p->nb_records); if (anm->page < 0) return anm->page; anm->record = -1; goto repeat; } /* fetch record size */ tmp = url_ftell(pb); url_fseek(pb, anm->page_table_offset + MAX_PAGES*6 + (anm->page<<16) + 8 + anm->record * 2, SEEK_SET); record_size = get_le16(pb); url_fseek(pb, tmp, SEEK_SET); /* fetch record */ pkt->size = av_get_packet(s->pb, pkt, record_size); if (pkt->size < 0) return pkt->size; if (p->base_record + anm->record == 0) pkt->flags |= AV_PKT_FLAG_KEY; anm->record++; return 0; } AVInputFormat anm_demuxer = { "anm", NULL_IF_CONFIG_SMALL("Deluxe Paint Animation"), sizeof(AnmDemuxContext), probe, read_header, read_packet, };
123linslouis-android-video-cutter
jni/libavformat/anm.c
C
asf20
6,495
/* * THP Demuxer * Copyright (c) 2007 Marco Gerards * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/intreadwrite.h" #include "avformat.h" typedef struct ThpDemuxContext { int version; int first_frame; int first_framesz; int last_frame; int compoff; int framecnt; AVRational fps; int frame; int next_frame; int next_framesz; int video_stream_index; int audio_stream_index; int compcount; unsigned char components[16]; AVStream* vst; int has_audio; int audiosize; } ThpDemuxContext; static int thp_probe(AVProbeData *p) { /* check file header */ if (AV_RL32(p->buf) == MKTAG('T', 'H', 'P', '\0')) return AVPROBE_SCORE_MAX; else return 0; } static int thp_read_header(AVFormatContext *s, AVFormatParameters *ap) { ThpDemuxContext *thp = s->priv_data; AVStream *st; ByteIOContext *pb = s->pb; int i; /* Read the file header. */ get_be32(pb); /* Skip Magic. */ thp->version = get_be32(pb); get_be32(pb); /* Max buf size. */ get_be32(pb); /* Max samples. */ thp->fps = av_d2q(av_int2flt(get_be32(pb)), INT_MAX); thp->framecnt = get_be32(pb); thp->first_framesz = get_be32(pb); get_be32(pb); /* Data size. */ thp->compoff = get_be32(pb); get_be32(pb); /* offsetDataOffset. */ thp->first_frame = get_be32(pb); thp->last_frame = get_be32(pb); thp->next_framesz = thp->first_framesz; thp->next_frame = thp->first_frame; /* Read the component structure. */ url_fseek (pb, thp->compoff, SEEK_SET); thp->compcount = get_be32(pb); /* Read the list of component types. */ get_buffer(pb, thp->components, 16); for (i = 0; i < thp->compcount; i++) { if (thp->components[i] == 0) { if (thp->vst != 0) break; /* Video component. */ st = av_new_stream(s, 0); if (!st) return AVERROR(ENOMEM); /* The denominator and numerator are switched because 1/fps is required. */ av_set_pts_info(st, 64, thp->fps.den, thp->fps.num); st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = CODEC_ID_THP; st->codec->codec_tag = 0; /* no fourcc */ st->codec->width = get_be32(pb); st->codec->height = get_be32(pb); st->codec->sample_rate = av_q2d(thp->fps); thp->vst = st; thp->video_stream_index = st->index; if (thp->version == 0x11000) get_be32(pb); /* Unknown. */ } else if (thp->components[i] == 1) { if (thp->has_audio != 0) break; /* Audio component. */ st = av_new_stream(s, 0); if (!st) return AVERROR(ENOMEM); st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_id = CODEC_ID_ADPCM_THP; st->codec->codec_tag = 0; /* no fourcc */ st->codec->channels = get_be32(pb); /* numChannels. */ st->codec->sample_rate = get_be32(pb); /* Frequency. */ av_set_pts_info(st, 64, 1, st->codec->sample_rate); thp->audio_stream_index = st->index; thp->has_audio = 1; } } return 0; } static int thp_read_packet(AVFormatContext *s, AVPacket *pkt) { ThpDemuxContext *thp = s->priv_data; ByteIOContext *pb = s->pb; int size; int ret; if (thp->audiosize == 0) { /* Terminate when last frame is reached. */ if (thp->frame >= thp->framecnt) return AVERROR(EIO); url_fseek(pb, thp->next_frame, SEEK_SET); /* Locate the next frame and read out its size. */ thp->next_frame += thp->next_framesz; thp->next_framesz = get_be32(pb); get_be32(pb); /* Previous total size. */ size = get_be32(pb); /* Total size of this frame. */ /* Store the audiosize so the next time this function is called, the audio can be read. */ if (thp->has_audio) thp->audiosize = get_be32(pb); /* Audio size. */ else thp->frame++; ret = av_get_packet(pb, pkt, size); if (ret != size) { av_free_packet(pkt); return AVERROR(EIO); } pkt->stream_index = thp->video_stream_index; } else { ret = av_get_packet(pb, pkt, thp->audiosize); if (ret != thp->audiosize) { av_free_packet(pkt); return AVERROR(EIO); } pkt->stream_index = thp->audio_stream_index; thp->audiosize = 0; thp->frame++; } return 0; } AVInputFormat thp_demuxer = { "thp", NULL_IF_CONFIG_SMALL("THP"), sizeof(ThpDemuxContext), thp_probe, thp_read_header, thp_read_packet };
123linslouis-android-video-cutter
jni/libavformat/thp.c
C
asf20
6,085
/* * RTP AMR Depacketizer, RFC 3267 * Copyright (c) 2010 Martin Storsjo * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_RTPDEC_AMR_H #define AVFORMAT_RTPDEC_AMR_H #include "rtpdec.h" extern RTPDynamicProtocolHandler ff_amr_nb_dynamic_handler; extern RTPDynamicProtocolHandler ff_amr_wb_dynamic_handler; #endif /* AVFORMAT_RTPDEC_AMR_H */
123linslouis-android-video-cutter
jni/libavformat/rtpdec_amr.h
C
asf20
1,076
/* * "NUT" Container Format (de)muxer * Copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_NUT_H #define AVFORMAT_NUT_H //#include <limits.h> //#include "libavutil/adler32.h" //#include "libavcodec/mpegaudio.h" #include "avformat.h" #include "riff.h" #include "metadata.h" #define MAIN_STARTCODE (0x7A561F5F04ADULL + (((uint64_t)('N'<<8) + 'M')<<48)) #define STREAM_STARTCODE (0x11405BF2F9DBULL + (((uint64_t)('N'<<8) + 'S')<<48)) #define SYNCPOINT_STARTCODE (0xE4ADEECA4569ULL + (((uint64_t)('N'<<8) + 'K')<<48)) #define INDEX_STARTCODE (0xDD672F23E64EULL + (((uint64_t)('N'<<8) + 'X')<<48)) #define INFO_STARTCODE (0xAB68B596BA78ULL + (((uint64_t)('N'<<8) + 'I')<<48)) #define ID_STRING "nut/multimedia container\0" #define MAX_DISTANCE (1024*32-1) typedef enum{ FLAG_KEY = 1, ///<if set, frame is keyframe FLAG_EOR = 2, ///<if set, stream has no relevance on presentation. (EOR) FLAG_CODED_PTS = 8, ///<if set, coded_pts is in the frame header FLAG_STREAM_ID = 16, ///<if set, stream_id is coded in the frame header FLAG_SIZE_MSB = 32, ///<if set, data_size_msb is at frame header, otherwise data_size_msb is 0 FLAG_CHECKSUM = 64, ///<if set, the frame header contains a checksum FLAG_RESERVED = 128, ///<if set, reserved_count is coded in the frame header FLAG_HEADER_IDX =1024, ///<If set, header_idx is coded in the frame header. FLAG_MATCH_TIME =2048, ///<If set, match_time_delta is coded in the frame header FLAG_CODED =4096, ///<if set, coded_flags are stored in the frame header FLAG_INVALID =8192, ///<if set, frame_code is invalid } Flag; typedef struct { uint64_t pos; uint64_t back_ptr; // uint64_t global_key_pts; int64_t ts; } Syncpoint; typedef struct { uint16_t flags; uint8_t stream_id; uint16_t size_mul; uint16_t size_lsb; int16_t pts_delta; uint8_t reserved_count; uint8_t header_idx; } FrameCode; typedef struct { int last_flags; int skip_until_key_frame; int64_t last_pts; int time_base_id; AVRational *time_base; int msb_pts_shift; int max_pts_distance; int decode_delay; //FIXME duplicate of has_b_frames } StreamContext; typedef struct { AVFormatContext *avf; // int written_packet_size; // int64_t packet_start; FrameCode frame_code[256]; uint8_t header_len[128]; const uint8_t *header[128]; uint64_t next_startcode; ///< stores the next startcode if it has already been parsed but the stream is not seekable StreamContext *stream; unsigned int max_distance; unsigned int time_base_count; int64_t last_syncpoint_pos; int header_count; AVRational *time_base; struct AVTreeNode *syncpoints; } NUTContext; extern const AVCodecTag ff_nut_subtitle_tags[]; typedef struct { char str[9]; int flag; } Dispositions; void ff_nut_reset_ts(NUTContext *nut, AVRational time_base, int64_t val); int64_t ff_lsb2full(StreamContext *stream, int64_t lsb); int ff_nut_sp_pos_cmp(const Syncpoint *a, const Syncpoint *b); int ff_nut_sp_pts_cmp(const Syncpoint *a, const Syncpoint *b); void ff_nut_add_sp(NUTContext *nut, int64_t pos, int64_t back_ptr, int64_t ts); void ff_nut_free_sp(NUTContext *nut); extern const Dispositions ff_nut_dispositions[]; extern const AVMetadataConv ff_nut_metadata_conv[]; #endif /* AVFORMAT_NUT_H */
123linslouis-android-video-cutter
jni/libavformat/nut.h
C
asf20
4,171
/* * Cyril Comparon, Larbi Joubala, Resonate-MP4 2009 * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_AVLANGUAGE_H #define AVFORMAT_AVLANGUAGE_H /** * Known language codespaces */ enum AVLangCodespace { AV_LANG_ISO639_2_BIBL, /** 3-char bibliographic language codes as per ISO-IEC 639-2 */ AV_LANG_ISO639_2_TERM, /** 3-char terminologic language codes as per ISO-IEC 639-2 */ AV_LANG_ISO639_1 /** 2-char code of language as per ISO/IEC 639-1 */ }; /** * Converts a language code to a target codespace. The source codespace is guessed. * Returns NULL if the provided lang is null or invalid. */ const char *av_convert_lang_to(const char *lang, enum AVLangCodespace target_codespace); #endif /* AVFORMAT_AVLANGUAGE_H */
123linslouis-android-video-cutter
jni/libavformat/avlanguage.h
C
asf20
1,478
/* * Image format * Copyright (c) 2000, 2001, 2002 Fabrice Bellard * Copyright (c) 2004 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/intreadwrite.h" #include "libavutil/avstring.h" #include "avformat.h" #include <strings.h> typedef struct { int img_first; int img_last; int img_number; int img_count; int is_pipe; char path[1024]; } VideoData; typedef struct { enum CodecID id; const char *str; } IdStrMap; static const IdStrMap img_tags[] = { { CODEC_ID_MJPEG , "jpeg"}, { CODEC_ID_MJPEG , "jpg"}, { CODEC_ID_LJPEG , "ljpg"}, { CODEC_ID_PNG , "png"}, { CODEC_ID_PNG , "mng"}, { CODEC_ID_PPM , "ppm"}, { CODEC_ID_PPM , "pnm"}, { CODEC_ID_PGM , "pgm"}, { CODEC_ID_PGMYUV , "pgmyuv"}, { CODEC_ID_PBM , "pbm"}, { CODEC_ID_PAM , "pam"}, { CODEC_ID_MPEG1VIDEO, "mpg1-img"}, { CODEC_ID_MPEG2VIDEO, "mpg2-img"}, { CODEC_ID_MPEG4 , "mpg4-img"}, { CODEC_ID_FFV1 , "ffv1-img"}, { CODEC_ID_RAWVIDEO , "y"}, { CODEC_ID_BMP , "bmp"}, { CODEC_ID_GIF , "gif"}, { CODEC_ID_TARGA , "tga"}, { CODEC_ID_TIFF , "tiff"}, { CODEC_ID_TIFF , "tif"}, { CODEC_ID_SGI , "sgi"}, { CODEC_ID_PTX , "ptx"}, { CODEC_ID_PCX , "pcx"}, { CODEC_ID_SUNRAST , "sun"}, { CODEC_ID_SUNRAST , "ras"}, { CODEC_ID_SUNRAST , "rs"}, { CODEC_ID_SUNRAST , "im1"}, { CODEC_ID_SUNRAST , "im8"}, { CODEC_ID_SUNRAST , "im24"}, { CODEC_ID_SUNRAST , "sunras"}, { CODEC_ID_JPEG2000 , "jp2"}, { CODEC_ID_DPX , "dpx"}, { CODEC_ID_NONE , NULL} }; static const int sizes[][2] = { { 640, 480 }, { 720, 480 }, { 720, 576 }, { 352, 288 }, { 352, 240 }, { 160, 128 }, { 512, 384 }, { 640, 352 }, { 640, 240 }, }; static int infer_size(int *width_ptr, int *height_ptr, int size) { int i; for(i=0;i<FF_ARRAY_ELEMS(sizes);i++) { if ((sizes[i][0] * sizes[i][1]) == size) { *width_ptr = sizes[i][0]; *height_ptr = sizes[i][1]; return 0; } } return -1; } static enum CodecID av_str2id(const IdStrMap *tags, const char *str) { str= strrchr(str, '.'); if(!str) return CODEC_ID_NONE; str++; while (tags->id) { if (!strcasecmp(str, tags->str)) return tags->id; tags++; } return CODEC_ID_NONE; } /* return -1 if no image found */ static int find_image_range(int *pfirst_index, int *plast_index, const char *path) { char buf[1024]; int range, last_index, range1, first_index; /* find the first image */ for(first_index = 0; first_index < 5; first_index++) { if (av_get_frame_filename(buf, sizeof(buf), path, first_index) < 0){ *pfirst_index = *plast_index = 1; if(url_exist(buf)) return 0; return -1; } if (url_exist(buf)) break; } if (first_index == 5) goto fail; /* find the last image */ last_index = first_index; for(;;) { range = 0; for(;;) { if (!range) range1 = 1; else range1 = 2 * range; if (av_get_frame_filename(buf, sizeof(buf), path, last_index + range1) < 0) goto fail; if (!url_exist(buf)) break; range = range1; /* just in case... */ if (range >= (1 << 30)) goto fail; } /* we are sure than image last_index + range exists */ if (!range) break; last_index += range; } *pfirst_index = first_index; *plast_index = last_index; return 0; fail: return -1; } static int image_probe(AVProbeData *p) { if (p->filename && av_str2id(img_tags, p->filename)) { if (av_filename_number_test(p->filename)) return AVPROBE_SCORE_MAX; else return AVPROBE_SCORE_MAX/2; } return 0; } enum CodecID av_guess_image2_codec(const char *filename){ return av_str2id(img_tags, filename); } static int img_read_header(AVFormatContext *s1, AVFormatParameters *ap) { VideoData *s = s1->priv_data; int first_index, last_index; AVStream *st; s1->ctx_flags |= AVFMTCTX_NOHEADER; st = av_new_stream(s1, 0); if (!st) { return AVERROR(ENOMEM); } av_strlcpy(s->path, s1->filename, sizeof(s->path)); s->img_number = 0; s->img_count = 0; /* find format */ if (s1->iformat->flags & AVFMT_NOFILE) s->is_pipe = 0; else{ s->is_pipe = 1; st->need_parsing = AVSTREAM_PARSE_FULL; } if (!ap->time_base.num) { av_set_pts_info(st, 60, 1, 25); } else { av_set_pts_info(st, 60, ap->time_base.num, ap->time_base.den); } if(ap->width && ap->height){ st->codec->width = ap->width; st->codec->height= ap->height; } if (!s->is_pipe) { if (find_image_range(&first_index, &last_index, s->path) < 0) return AVERROR(ENOENT); s->img_first = first_index; s->img_last = last_index; s->img_number = first_index; /* compute duration */ st->start_time = 0; st->duration = last_index - first_index + 1; } if(s1->video_codec_id){ st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = s1->video_codec_id; }else if(s1->audio_codec_id){ st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_id = s1->audio_codec_id; }else{ st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = av_str2id(img_tags, s->path); } if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ap->pix_fmt != PIX_FMT_NONE) st->codec->pix_fmt = ap->pix_fmt; return 0; } static int img_read_packet(AVFormatContext *s1, AVPacket *pkt) { VideoData *s = s1->priv_data; char filename[1024]; int i; int size[3]={0}, ret[3]={0}; ByteIOContext *f[3]; AVCodecContext *codec= s1->streams[0]->codec; if (!s->is_pipe) { /* loop over input */ if (s1->loop_input && s->img_number > s->img_last) { s->img_number = s->img_first; } if (s->img_number > s->img_last) return AVERROR_EOF; if (av_get_frame_filename(filename, sizeof(filename), s->path, s->img_number)<0 && s->img_number > 1) return AVERROR(EIO); for(i=0; i<3; i++){ if (url_fopen(&f[i], filename, URL_RDONLY) < 0) { if(i==1) break; av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",filename); return AVERROR(EIO); } size[i]= url_fsize(f[i]); if(codec->codec_id != CODEC_ID_RAWVIDEO) break; filename[ strlen(filename) - 1 ]= 'U' + i; } if(codec->codec_id == CODEC_ID_RAWVIDEO && !codec->width) infer_size(&codec->width, &codec->height, size[0]); } else { f[0] = s1->pb; if (url_feof(f[0])) return AVERROR(EIO); size[0]= 4096; } av_new_packet(pkt, size[0] + size[1] + size[2]); pkt->stream_index = 0; pkt->flags |= AV_PKT_FLAG_KEY; pkt->size= 0; for(i=0; i<3; i++){ if(size[i]){ ret[i]= get_buffer(f[i], pkt->data + pkt->size, size[i]); if (!s->is_pipe) url_fclose(f[i]); if(ret[i]>0) pkt->size += ret[i]; } } if (ret[0] <= 0 || ret[1]<0 || ret[2]<0) { av_free_packet(pkt); return AVERROR(EIO); /* signal EOF */ } else { s->img_count++; s->img_number++; return 0; } } #if CONFIG_IMAGE2_MUXER || CONFIG_IMAGE2PIPE_MUXER /******************************************************/ /* image output */ static int img_write_header(AVFormatContext *s) { VideoData *img = s->priv_data; img->img_number = 1; av_strlcpy(img->path, s->filename, sizeof(img->path)); /* find format */ if (s->oformat->flags & AVFMT_NOFILE) img->is_pipe = 0; else img->is_pipe = 1; return 0; } static int img_write_packet(AVFormatContext *s, AVPacket *pkt) { VideoData *img = s->priv_data; ByteIOContext *pb[3]; char filename[1024]; AVCodecContext *codec= s->streams[ pkt->stream_index ]->codec; int i; if (!img->is_pipe) { if (av_get_frame_filename(filename, sizeof(filename), img->path, img->img_number) < 0 && img->img_number>1) { av_log(s, AV_LOG_ERROR, "Could not get frame filename from pattern\n"); return AVERROR(EIO); } for(i=0; i<3; i++){ if (url_fopen(&pb[i], filename, URL_WRONLY) < 0) { av_log(s, AV_LOG_ERROR, "Could not open file : %s\n",filename); return AVERROR(EIO); } if(codec->codec_id != CODEC_ID_RAWVIDEO) break; filename[ strlen(filename) - 1 ]= 'U' + i; } } else { pb[0] = s->pb; } if(codec->codec_id == CODEC_ID_RAWVIDEO){ int ysize = codec->width * codec->height; put_buffer(pb[0], pkt->data , ysize); put_buffer(pb[1], pkt->data + ysize, (pkt->size - ysize)/2); put_buffer(pb[2], pkt->data + ysize +(pkt->size - ysize)/2, (pkt->size - ysize)/2); put_flush_packet(pb[1]); put_flush_packet(pb[2]); url_fclose(pb[1]); url_fclose(pb[2]); }else{ if(av_str2id(img_tags, s->filename) == CODEC_ID_JPEG2000){ AVStream *st = s->streams[0]; if(st->codec->extradata_size > 8 && AV_RL32(st->codec->extradata+4) == MKTAG('j','p','2','h')){ if(pkt->size < 8 || AV_RL32(pkt->data+4) != MKTAG('j','p','2','c')) goto error; put_be32(pb[0], 12); put_tag (pb[0], "jP "); put_be32(pb[0], 0x0D0A870A); // signature put_be32(pb[0], 20); put_tag (pb[0], "ftyp"); put_tag (pb[0], "jp2 "); put_be32(pb[0], 0); put_tag (pb[0], "jp2 "); put_buffer(pb[0], st->codec->extradata, st->codec->extradata_size); }else if(pkt->size < 8 || (!st->codec->extradata_size && AV_RL32(pkt->data+4) != MKTAG('j','P',' ',' '))){ // signature error: av_log(s, AV_LOG_ERROR, "malformated jpeg2000 codestream\n"); return -1; } } put_buffer(pb[0], pkt->data, pkt->size); } put_flush_packet(pb[0]); if (!img->is_pipe) { url_fclose(pb[0]); } img->img_number++; return 0; } #endif /* CONFIG_IMAGE2_MUXER || CONFIG_IMAGE2PIPE_MUXER */ /* input */ #if CONFIG_IMAGE2_DEMUXER AVInputFormat image2_demuxer = { "image2", NULL_IF_CONFIG_SMALL("image2 sequence"), sizeof(VideoData), image_probe, img_read_header, img_read_packet, NULL, NULL, NULL, AVFMT_NOFILE, }; #endif #if CONFIG_IMAGE2PIPE_DEMUXER AVInputFormat image2pipe_demuxer = { "image2pipe", NULL_IF_CONFIG_SMALL("piped image2 sequence"), sizeof(VideoData), NULL, /* no probe */ img_read_header, img_read_packet, }; #endif /* output */ #if CONFIG_IMAGE2_MUXER AVOutputFormat image2_muxer = { "image2", NULL_IF_CONFIG_SMALL("image2 sequence"), "", "bmp,jpeg,jpg,ljpg,pam,pbm,pcx,pgm,pgmyuv,png,ppm,sgi,tif,tiff,jp2", sizeof(VideoData), CODEC_ID_NONE, CODEC_ID_MJPEG, img_write_header, img_write_packet, NULL, .flags= AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS | AVFMT_NOFILE }; #endif #if CONFIG_IMAGE2PIPE_MUXER AVOutputFormat image2pipe_muxer = { "image2pipe", NULL_IF_CONFIG_SMALL("piped image2 sequence"), "", "", sizeof(VideoData), CODEC_ID_NONE, CODEC_ID_MJPEG, img_write_header, img_write_packet, .flags= AVFMT_NOTIMESTAMPS | AVFMT_NODIMENSIONS }; #endif
123linslouis-android-video-cutter
jni/libavformat/img2.c
C
asf20
13,144
/* * Electronic Arts .cdata file Demuxer * Copyright (c) 2007 Peter Ross * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Electronic Arts cdata Format Demuxer * by Peter Ross (pross@xvid.org) * * Technical details here: * http://wiki.multimedia.cx/index.php?title=EA_Command_And_Conquer_3_Audio_Codec */ #include "avformat.h" typedef struct { unsigned int channels; unsigned int audio_pts; } CdataDemuxContext; static int cdata_probe(AVProbeData *p) { const uint8_t *b = p->buf; if (b[0] == 0x04 && (b[1] == 0x00 || b[1] == 0x04 || b[1] == 0x0C)) return AVPROBE_SCORE_MAX/8; return 0; } static int cdata_read_header(AVFormatContext *s, AVFormatParameters *ap) { CdataDemuxContext *cdata = s->priv_data; ByteIOContext *pb = s->pb; unsigned int sample_rate, header; AVStream *st; header = get_be16(pb); switch (header) { case 0x0400: cdata->channels = 1; break; case 0x0404: cdata->channels = 2; break; case 0x040C: cdata->channels = 4; break; default: av_log(s, AV_LOG_INFO, "unknown header 0x%04x\n", header); return -1; }; sample_rate = get_be16(pb); url_fskip(pb, 12); st = av_new_stream(s, 0); if (!st) return AVERROR(ENOMEM); st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_tag = 0; /* no fourcc */ st->codec->codec_id = CODEC_ID_ADPCM_EA_XAS; st->codec->channels = cdata->channels; st->codec->sample_rate = sample_rate; av_set_pts_info(st, 64, 1, sample_rate); cdata->audio_pts = 0; return 0; } static int cdata_read_packet(AVFormatContext *s, AVPacket *pkt) { CdataDemuxContext *cdata = s->priv_data; int packet_size = 76*cdata->channels; int ret = av_get_packet(s->pb, pkt, packet_size); if (ret < 0) return ret; pkt->pts = cdata->audio_pts++; return 0; } AVInputFormat ea_cdata_demuxer = { "ea_cdata", NULL_IF_CONFIG_SMALL("Electronic Arts cdata"), sizeof(CdataDemuxContext), cdata_probe, cdata_read_header, cdata_read_packet, .extensions = "cdata", };
123linslouis-android-video-cutter
jni/libavformat/eacdata.c
C
asf20
2,849
/* * RTP output format * Copyright (c) 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avformat.h" #include "mpegts.h" #include "internal.h" #include "libavutil/random_seed.h" #include <unistd.h> #include "rtpenc.h" //#define DEBUG #define RTCP_SR_SIZE 28 static int is_supported(enum CodecID id) { switch(id) { case CODEC_ID_H263: case CODEC_ID_H263P: case CODEC_ID_H264: case CODEC_ID_MPEG1VIDEO: case CODEC_ID_MPEG2VIDEO: case CODEC_ID_MPEG4: case CODEC_ID_AAC: case CODEC_ID_MP2: case CODEC_ID_MP3: case CODEC_ID_PCM_ALAW: case CODEC_ID_PCM_MULAW: case CODEC_ID_PCM_S8: case CODEC_ID_PCM_S16BE: case CODEC_ID_PCM_S16LE: case CODEC_ID_PCM_U16BE: case CODEC_ID_PCM_U16LE: case CODEC_ID_PCM_U8: case CODEC_ID_MPEG2TS: case CODEC_ID_AMR_NB: case CODEC_ID_AMR_WB: return 1; default: return 0; } } static int rtp_write_header(AVFormatContext *s1) { RTPMuxContext *s = s1->priv_data; int max_packet_size, n; AVStream *st; if (s1->nb_streams != 1) return -1; st = s1->streams[0]; if (!is_supported(st->codec->codec_id)) { av_log(s1, AV_LOG_ERROR, "Unsupported codec %x\n", st->codec->codec_id); return -1; } s->payload_type = ff_rtp_get_payload_type(st->codec); if (s->payload_type < 0) s->payload_type = RTP_PT_PRIVATE + (st->codec->codec_type == AVMEDIA_TYPE_AUDIO); s->base_timestamp = ff_random_get_seed(); s->timestamp = s->base_timestamp; s->cur_timestamp = 0; s->ssrc = ff_random_get_seed(); s->first_packet = 1; s->first_rtcp_ntp_time = ff_ntp_time(); if (s1->start_time_realtime) /* Round the NTP time to whole milliseconds. */ s->first_rtcp_ntp_time = (s1->start_time_realtime / 1000) * 1000 + NTP_OFFSET_US; max_packet_size = url_fget_max_packet_size(s1->pb); if (max_packet_size <= 12) return AVERROR(EIO); s->buf = av_malloc(max_packet_size); if (s->buf == NULL) { return AVERROR(ENOMEM); } s->max_payload_size = max_packet_size - 12; s->max_frames_per_packet = 0; if (s1->max_delay) { if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) { if (st->codec->frame_size == 0) { av_log(s1, AV_LOG_ERROR, "Cannot respect max delay: frame size = 0\n"); } else { s->max_frames_per_packet = av_rescale_rnd(s1->max_delay, st->codec->sample_rate, AV_TIME_BASE * st->codec->frame_size, AV_ROUND_DOWN); } } if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) { /* FIXME: We should round down here... */ s->max_frames_per_packet = av_rescale_q(s1->max_delay, (AVRational){1, 1000000}, st->codec->time_base); } } av_set_pts_info(st, 32, 1, 90000); switch(st->codec->codec_id) { case CODEC_ID_MP2: case CODEC_ID_MP3: s->buf_ptr = s->buf + 4; break; case CODEC_ID_MPEG1VIDEO: case CODEC_ID_MPEG2VIDEO: break; case CODEC_ID_MPEG2TS: n = s->max_payload_size / TS_PACKET_SIZE; if (n < 1) n = 1; s->max_payload_size = n * TS_PACKET_SIZE; s->buf_ptr = s->buf; break; case CODEC_ID_AMR_NB: case CODEC_ID_AMR_WB: if (!s->max_frames_per_packet) s->max_frames_per_packet = 12; if (st->codec->codec_id == CODEC_ID_AMR_NB) n = 31; else n = 61; /* max_header_toc_size + the largest AMR payload must fit */ if (1 + s->max_frames_per_packet + n > s->max_payload_size) { av_log(s1, AV_LOG_ERROR, "RTP max payload size too small for AMR\n"); return -1; } if (st->codec->channels != 1) { av_log(s1, AV_LOG_ERROR, "Only mono is supported\n"); return -1; } case CODEC_ID_AAC: s->num_frames = 0; default: if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) { av_set_pts_info(st, 32, 1, st->codec->sample_rate); } s->buf_ptr = s->buf; break; } return 0; } /* send an rtcp sender report packet */ static void rtcp_send_sr(AVFormatContext *s1, int64_t ntp_time) { RTPMuxContext *s = s1->priv_data; uint32_t rtp_ts; dprintf(s1, "RTCP: %02x %"PRIx64" %x\n", s->payload_type, ntp_time, s->timestamp); s->last_rtcp_ntp_time = ntp_time; rtp_ts = av_rescale_q(ntp_time - s->first_rtcp_ntp_time, (AVRational){1, 1000000}, s1->streams[0]->time_base) + s->base_timestamp; put_byte(s1->pb, (RTP_VERSION << 6)); put_byte(s1->pb, 200); put_be16(s1->pb, 6); /* length in words - 1 */ put_be32(s1->pb, s->ssrc); put_be32(s1->pb, ntp_time / 1000000); put_be32(s1->pb, ((ntp_time % 1000000) << 32) / 1000000); put_be32(s1->pb, rtp_ts); put_be32(s1->pb, s->packet_count); put_be32(s1->pb, s->octet_count); put_flush_packet(s1->pb); } /* send an rtp packet. sequence number is incremented, but the caller must update the timestamp itself */ void ff_rtp_send_data(AVFormatContext *s1, const uint8_t *buf1, int len, int m) { RTPMuxContext *s = s1->priv_data; dprintf(s1, "rtp_send_data size=%d\n", len); /* build the RTP header */ put_byte(s1->pb, (RTP_VERSION << 6)); put_byte(s1->pb, (s->payload_type & 0x7f) | ((m & 0x01) << 7)); put_be16(s1->pb, s->seq); put_be32(s1->pb, s->timestamp); put_be32(s1->pb, s->ssrc); put_buffer(s1->pb, buf1, len); put_flush_packet(s1->pb); s->seq++; s->octet_count += len; s->packet_count++; } /* send an integer number of samples and compute time stamp and fill the rtp send buffer before sending. */ static void rtp_send_samples(AVFormatContext *s1, const uint8_t *buf1, int size, int sample_size) { RTPMuxContext *s = s1->priv_data; int len, max_packet_size, n; max_packet_size = (s->max_payload_size / sample_size) * sample_size; /* not needed, but who nows */ if ((size % sample_size) != 0) av_abort(); n = 0; while (size > 0) { s->buf_ptr = s->buf; len = FFMIN(max_packet_size, size); /* copy data */ memcpy(s->buf_ptr, buf1, len); s->buf_ptr += len; buf1 += len; size -= len; s->timestamp = s->cur_timestamp + n / sample_size; ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0); n += (s->buf_ptr - s->buf); } } static void rtp_send_mpegaudio(AVFormatContext *s1, const uint8_t *buf1, int size) { RTPMuxContext *s = s1->priv_data; int len, count, max_packet_size; max_packet_size = s->max_payload_size; /* test if we must flush because not enough space */ len = (s->buf_ptr - s->buf); if ((len + size) > max_packet_size) { if (len > 4) { ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0); s->buf_ptr = s->buf + 4; } } if (s->buf_ptr == s->buf + 4) { s->timestamp = s->cur_timestamp; } /* add the packet */ if (size > max_packet_size) { /* big packet: fragment */ count = 0; while (size > 0) { len = max_packet_size - 4; if (len > size) len = size; /* build fragmented packet */ s->buf[0] = 0; s->buf[1] = 0; s->buf[2] = count >> 8; s->buf[3] = count; memcpy(s->buf + 4, buf1, len); ff_rtp_send_data(s1, s->buf, len + 4, 0); size -= len; buf1 += len; count += len; } } else { if (s->buf_ptr == s->buf + 4) { /* no fragmentation possible */ s->buf[0] = 0; s->buf[1] = 0; s->buf[2] = 0; s->buf[3] = 0; } memcpy(s->buf_ptr, buf1, size); s->buf_ptr += size; } } static void rtp_send_raw(AVFormatContext *s1, const uint8_t *buf1, int size) { RTPMuxContext *s = s1->priv_data; int len, max_packet_size; max_packet_size = s->max_payload_size; while (size > 0) { len = max_packet_size; if (len > size) len = size; s->timestamp = s->cur_timestamp; ff_rtp_send_data(s1, buf1, len, (len == size)); buf1 += len; size -= len; } } /* NOTE: size is assumed to be an integer multiple of TS_PACKET_SIZE */ static void rtp_send_mpegts_raw(AVFormatContext *s1, const uint8_t *buf1, int size) { RTPMuxContext *s = s1->priv_data; int len, out_len; while (size >= TS_PACKET_SIZE) { len = s->max_payload_size - (s->buf_ptr - s->buf); if (len > size) len = size; memcpy(s->buf_ptr, buf1, len); buf1 += len; size -= len; s->buf_ptr += len; out_len = s->buf_ptr - s->buf; if (out_len >= s->max_payload_size) { ff_rtp_send_data(s1, s->buf, out_len, 0); s->buf_ptr = s->buf; } } } static int rtp_write_packet(AVFormatContext *s1, AVPacket *pkt) { RTPMuxContext *s = s1->priv_data; AVStream *st = s1->streams[0]; int rtcp_bytes; int size= pkt->size; dprintf(s1, "%d: write len=%d\n", pkt->stream_index, size); rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) / RTCP_TX_RATIO_DEN; if (s->first_packet || ((rtcp_bytes >= RTCP_SR_SIZE) && (ff_ntp_time() - s->last_rtcp_ntp_time > 5000000))) { rtcp_send_sr(s1, ff_ntp_time()); s->last_octet_count = s->octet_count; s->first_packet = 0; } s->cur_timestamp = s->base_timestamp + pkt->pts; switch(st->codec->codec_id) { case CODEC_ID_PCM_MULAW: case CODEC_ID_PCM_ALAW: case CODEC_ID_PCM_U8: case CODEC_ID_PCM_S8: rtp_send_samples(s1, pkt->data, size, 1 * st->codec->channels); break; case CODEC_ID_PCM_U16BE: case CODEC_ID_PCM_U16LE: case CODEC_ID_PCM_S16BE: case CODEC_ID_PCM_S16LE: rtp_send_samples(s1, pkt->data, size, 2 * st->codec->channels); break; case CODEC_ID_MP2: case CODEC_ID_MP3: rtp_send_mpegaudio(s1, pkt->data, size); break; case CODEC_ID_MPEG1VIDEO: case CODEC_ID_MPEG2VIDEO: ff_rtp_send_mpegvideo(s1, pkt->data, size); break; case CODEC_ID_AAC: ff_rtp_send_aac(s1, pkt->data, size); break; case CODEC_ID_AMR_NB: case CODEC_ID_AMR_WB: ff_rtp_send_amr(s1, pkt->data, size); break; case CODEC_ID_MPEG2TS: rtp_send_mpegts_raw(s1, pkt->data, size); break; case CODEC_ID_H264: ff_rtp_send_h264(s1, pkt->data, size); break; case CODEC_ID_H263: case CODEC_ID_H263P: ff_rtp_send_h263(s1, pkt->data, size); break; default: /* better than nothing : send the codec raw data */ rtp_send_raw(s1, pkt->data, size); break; } return 0; } static int rtp_write_trailer(AVFormatContext *s1) { RTPMuxContext *s = s1->priv_data; av_freep(&s->buf); return 0; } AVOutputFormat rtp_muxer = { "rtp", NULL_IF_CONFIG_SMALL("RTP output format"), NULL, NULL, sizeof(RTPMuxContext), CODEC_ID_PCM_MULAW, CODEC_ID_NONE, rtp_write_header, rtp_write_packet, rtp_write_trailer, };
123linslouis-android-video-cutter
jni/libavformat/rtpenc.c
C
asf20
12,314
/* * id RoQ (.roq) File Demuxer * Copyright (c) 2003 The ffmpeg Project * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * id RoQ format file demuxer * by Mike Melanson (melanson@pcisys.net) * for more information on the .roq file format, visit: * http://www.csse.monash.edu.au/~timf/ */ #include "libavutil/intreadwrite.h" #include "avformat.h" #define RoQ_MAGIC_NUMBER 0x1084 #define RoQ_CHUNK_PREAMBLE_SIZE 8 #define RoQ_AUDIO_SAMPLE_RATE 22050 #define RoQ_CHUNKS_TO_SCAN 30 #define RoQ_INFO 0x1001 #define RoQ_QUAD_CODEBOOK 0x1002 #define RoQ_QUAD_VQ 0x1011 #define RoQ_SOUND_MONO 0x1020 #define RoQ_SOUND_STEREO 0x1021 typedef struct RoqDemuxContext { int width; int height; int audio_channels; int video_stream_index; int audio_stream_index; int64_t video_pts; unsigned int audio_frame_count; } RoqDemuxContext; static int roq_probe(AVProbeData *p) { if ((AV_RL16(&p->buf[0]) != RoQ_MAGIC_NUMBER) || (AV_RL32(&p->buf[2]) != 0xFFFFFFFF)) return 0; return AVPROBE_SCORE_MAX; } static int roq_read_header(AVFormatContext *s, AVFormatParameters *ap) { RoqDemuxContext *roq = s->priv_data; ByteIOContext *pb = s->pb; int framerate; AVStream *st; unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE]; /* get the main header */ if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) != RoQ_CHUNK_PREAMBLE_SIZE) return AVERROR(EIO); framerate = AV_RL16(&preamble[6]); /* init private context parameters */ roq->width = roq->height = roq->audio_channels = roq->video_pts = roq->audio_frame_count = 0; roq->audio_stream_index = -1; st = av_new_stream(s, 0); if (!st) return AVERROR(ENOMEM); av_set_pts_info(st, 63, 1, framerate); roq->video_stream_index = st->index; st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = CODEC_ID_ROQ; st->codec->codec_tag = 0; /* no fourcc */ return 0; } static int roq_read_packet(AVFormatContext *s, AVPacket *pkt) { RoqDemuxContext *roq = s->priv_data; ByteIOContext *pb = s->pb; int ret = 0; unsigned int chunk_size; unsigned int chunk_type; unsigned int codebook_size; unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE]; int packet_read = 0; int64_t codebook_offset; while (!packet_read) { if (url_feof(s->pb)) return AVERROR(EIO); /* get the next chunk preamble */ if ((ret = get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE)) != RoQ_CHUNK_PREAMBLE_SIZE) return AVERROR(EIO); chunk_type = AV_RL16(&preamble[0]); chunk_size = AV_RL32(&preamble[2]); if(chunk_size > INT_MAX) return AVERROR_INVALIDDATA; switch (chunk_type) { case RoQ_INFO: if (!roq->width || !roq->height) { AVStream *st = s->streams[roq->video_stream_index]; if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) != RoQ_CHUNK_PREAMBLE_SIZE) return AVERROR(EIO); st->codec->width = roq->width = AV_RL16(preamble); st->codec->height = roq->height = AV_RL16(preamble + 2); break; } /* don't care about this chunk anymore */ url_fseek(pb, RoQ_CHUNK_PREAMBLE_SIZE, SEEK_CUR); break; case RoQ_QUAD_CODEBOOK: /* packet needs to contain both this codebook and next VQ chunk */ codebook_offset = url_ftell(pb) - RoQ_CHUNK_PREAMBLE_SIZE; codebook_size = chunk_size; url_fseek(pb, codebook_size, SEEK_CUR); if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) != RoQ_CHUNK_PREAMBLE_SIZE) return AVERROR(EIO); chunk_size = AV_RL32(&preamble[2]) + RoQ_CHUNK_PREAMBLE_SIZE * 2 + codebook_size; /* rewind */ url_fseek(pb, codebook_offset, SEEK_SET); /* load up the packet */ ret= av_get_packet(pb, pkt, chunk_size); if (ret != chunk_size) return AVERROR(EIO); pkt->stream_index = roq->video_stream_index; pkt->pts = roq->video_pts++; packet_read = 1; break; case RoQ_SOUND_MONO: case RoQ_SOUND_STEREO: if (roq->audio_stream_index == -1) { AVStream *st = av_new_stream(s, 1); if (!st) return AVERROR(ENOMEM); av_set_pts_info(st, 32, 1, RoQ_AUDIO_SAMPLE_RATE); roq->audio_stream_index = st->index; st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_id = CODEC_ID_ROQ_DPCM; st->codec->codec_tag = 0; /* no tag */ st->codec->channels = roq->audio_channels = chunk_type == RoQ_SOUND_STEREO ? 2 : 1; st->codec->sample_rate = RoQ_AUDIO_SAMPLE_RATE; st->codec->bits_per_coded_sample = 16; st->codec->bit_rate = st->codec->channels * st->codec->sample_rate * st->codec->bits_per_coded_sample; st->codec->block_align = st->codec->channels * st->codec->bits_per_coded_sample; } case RoQ_QUAD_VQ: /* load up the packet */ if (av_new_packet(pkt, chunk_size + RoQ_CHUNK_PREAMBLE_SIZE)) return AVERROR(EIO); /* copy over preamble */ memcpy(pkt->data, preamble, RoQ_CHUNK_PREAMBLE_SIZE); if (chunk_type == RoQ_QUAD_VQ) { pkt->stream_index = roq->video_stream_index; pkt->pts = roq->video_pts++; } else { pkt->stream_index = roq->audio_stream_index; pkt->pts = roq->audio_frame_count; roq->audio_frame_count += (chunk_size / roq->audio_channels); } pkt->pos= url_ftell(pb); ret = get_buffer(pb, pkt->data + RoQ_CHUNK_PREAMBLE_SIZE, chunk_size); if (ret != chunk_size) ret = AVERROR(EIO); packet_read = 1; break; default: av_log(s, AV_LOG_ERROR, " unknown RoQ chunk (%04X)\n", chunk_type); return AVERROR_INVALIDDATA; break; } } return ret; } AVInputFormat roq_demuxer = { "RoQ", NULL_IF_CONFIG_SMALL("id RoQ format"), sizeof(RoqDemuxContext), roq_probe, roq_read_header, roq_read_packet, };
123linslouis-android-video-cutter
jni/libavformat/idroq.c
C
asf20
7,384
/* * 8088flex TMV file demuxer * Copyright (c) 2009 Daniel Verkamp <daniel at drv.nu> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * 8088flex TMV file demuxer * @file * @author Daniel Verkamp * @sa http://www.oldskool.org/pc/8088_Corruption */ #include "libavutil/intreadwrite.h" #include "avformat.h" enum { TMV_PADDING = 0x01, TMV_STEREO = 0x02, }; #define TMV_TAG MKTAG('T', 'M', 'A', 'V') typedef struct TMVContext { unsigned audio_chunk_size; unsigned video_chunk_size; unsigned padding; unsigned stream_index; } TMVContext; #define TMV_HEADER_SIZE 12 #define PROBE_MIN_SAMPLE_RATE 5000 #define PROBE_MAX_FPS 120 #define PROBE_MIN_AUDIO_SIZE (PROBE_MIN_SAMPLE_RATE / PROBE_MAX_FPS) static int tmv_probe(AVProbeData *p) { if (AV_RL32(p->buf) == TMV_TAG && AV_RL16(p->buf+4) >= PROBE_MIN_SAMPLE_RATE && AV_RL16(p->buf+6) >= PROBE_MIN_AUDIO_SIZE && !p->buf[8] && // compression method p->buf[9] && // char cols p->buf[10]) // char rows return AVPROBE_SCORE_MAX / ((p->buf[9] == 40 && p->buf[10] == 25) ? 1 : 4); return 0; } static int tmv_read_header(AVFormatContext *s, AVFormatParameters *ap) { TMVContext *tmv = s->priv_data; ByteIOContext *pb = s->pb; AVStream *vst, *ast; AVRational fps; unsigned comp_method, char_cols, char_rows, features; if (get_le32(pb) != TMV_TAG) return -1; if (!(vst = av_new_stream(s, 0))) return AVERROR(ENOMEM); if (!(ast = av_new_stream(s, 0))) return AVERROR(ENOMEM); ast->codec->sample_rate = get_le16(pb); if (!ast->codec->sample_rate) { av_log(s, AV_LOG_ERROR, "invalid sample rate\n"); return -1; } tmv->audio_chunk_size = get_le16(pb); if (!tmv->audio_chunk_size) { av_log(s, AV_LOG_ERROR, "invalid audio chunk size\n"); return -1; } comp_method = get_byte(pb); if (comp_method) { av_log(s, AV_LOG_ERROR, "unsupported compression method %d\n", comp_method); return -1; } char_cols = get_byte(pb); char_rows = get_byte(pb); tmv->video_chunk_size = char_cols * char_rows * 2; features = get_byte(pb); if (features & ~(TMV_PADDING | TMV_STEREO)) { av_log(s, AV_LOG_ERROR, "unsupported features 0x%02x\n", features & ~(TMV_PADDING | TMV_STEREO)); return -1; } ast->codec->codec_type = AVMEDIA_TYPE_AUDIO; ast->codec->codec_id = CODEC_ID_PCM_U8; ast->codec->channels = features & TMV_STEREO ? 2 : 1; ast->codec->bits_per_coded_sample = 8; ast->codec->bit_rate = ast->codec->sample_rate * ast->codec->bits_per_coded_sample; av_set_pts_info(ast, 32, 1, ast->codec->sample_rate); fps.num = ast->codec->sample_rate * ast->codec->channels; fps.den = tmv->audio_chunk_size; av_reduce(&fps.num, &fps.den, fps.num, fps.den, 0xFFFFFFFFLL); vst->codec->codec_type = AVMEDIA_TYPE_VIDEO; vst->codec->codec_id = CODEC_ID_TMV; vst->codec->pix_fmt = PIX_FMT_PAL8; vst->codec->width = char_cols * 8; vst->codec->height = char_rows * 8; av_set_pts_info(vst, 32, fps.den, fps.num); if (features & TMV_PADDING) tmv->padding = ((tmv->video_chunk_size + tmv->audio_chunk_size + 511) & ~511) - (tmv->video_chunk_size + tmv->audio_chunk_size); vst->codec->bit_rate = ((tmv->video_chunk_size + tmv->padding) * fps.num * 8) / fps.den; return 0; } static int tmv_read_packet(AVFormatContext *s, AVPacket *pkt) { TMVContext *tmv = s->priv_data; ByteIOContext *pb = s->pb; int ret, pkt_size = tmv->stream_index ? tmv->audio_chunk_size : tmv->video_chunk_size; if (url_feof(pb)) return AVERROR_EOF; ret = av_get_packet(pb, pkt, pkt_size); if (tmv->stream_index) url_fskip(pb, tmv->padding); pkt->stream_index = tmv->stream_index; tmv->stream_index ^= 1; pkt->flags |= AV_PKT_FLAG_KEY; return ret; } static int tmv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { TMVContext *tmv = s->priv_data; int64_t pos; if (stream_index) return -1; pos = timestamp * (tmv->audio_chunk_size + tmv->video_chunk_size + tmv->padding); url_fseek(s->pb, pos + TMV_HEADER_SIZE, SEEK_SET); tmv->stream_index = 0; return 0; } AVInputFormat tmv_demuxer = { "tmv", NULL_IF_CONFIG_SMALL("8088flex TMV"), sizeof(TMVContext), tmv_probe, tmv_read_header, tmv_read_packet, NULL, tmv_read_seek, .flags = AVFMT_GENERIC_INDEX, };
123linslouis-android-video-cutter
jni/libavformat/tmv.c
C
asf20
5,597
/* * FFM (ffserver live feed) muxer * Copyright (c) 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/intreadwrite.h" #include "avformat.h" #include "ffm.h" static void flush_packet(AVFormatContext *s) { FFMContext *ffm = s->priv_data; int fill_size, h; ByteIOContext *pb = s->pb; fill_size = ffm->packet_end - ffm->packet_ptr; memset(ffm->packet_ptr, 0, fill_size); if (url_ftell(pb) % ffm->packet_size) av_abort(); /* put header */ put_be16(pb, PACKET_ID); put_be16(pb, fill_size); put_be64(pb, ffm->dts); h = ffm->frame_offset; if (ffm->first_packet) h |= 0x8000; put_be16(pb, h); put_buffer(pb, ffm->packet, ffm->packet_end - ffm->packet); put_flush_packet(pb); /* prepare next packet */ ffm->frame_offset = 0; /* no key frame */ ffm->packet_ptr = ffm->packet; ffm->first_packet = 0; } /* 'first' is true if first data of a frame */ static void ffm_write_data(AVFormatContext *s, const uint8_t *buf, int size, int64_t dts, int header) { FFMContext *ffm = s->priv_data; int len; if (header && ffm->frame_offset == 0) { ffm->frame_offset = ffm->packet_ptr - ffm->packet + FFM_HEADER_SIZE; ffm->dts = dts; } /* write as many packets as needed */ while (size > 0) { len = ffm->packet_end - ffm->packet_ptr; if (len > size) len = size; memcpy(ffm->packet_ptr, buf, len); ffm->packet_ptr += len; buf += len; size -= len; if (ffm->packet_ptr >= ffm->packet_end) flush_packet(s); } } static int ffm_write_header(AVFormatContext *s) { FFMContext *ffm = s->priv_data; AVStream *st; ByteIOContext *pb = s->pb; AVCodecContext *codec; int bit_rate, i; ffm->packet_size = FFM_PACKET_SIZE; /* header */ put_le32(pb, MKTAG('F', 'F', 'M', '1')); put_be32(pb, ffm->packet_size); put_be64(pb, 0); /* current write position */ put_be32(pb, s->nb_streams); bit_rate = 0; for(i=0;i<s->nb_streams;i++) { st = s->streams[i]; bit_rate += st->codec->bit_rate; } put_be32(pb, bit_rate); /* list of streams */ for(i=0;i<s->nb_streams;i++) { st = s->streams[i]; av_set_pts_info(st, 64, 1, 1000000); codec = st->codec; /* generic info */ put_be32(pb, codec->codec_id); put_byte(pb, codec->codec_type); put_be32(pb, codec->bit_rate); put_be32(pb, st->quality); put_be32(pb, codec->flags); put_be32(pb, codec->flags2); put_be32(pb, codec->debug); /* specific info */ switch(codec->codec_type) { case AVMEDIA_TYPE_VIDEO: put_be32(pb, codec->time_base.num); put_be32(pb, codec->time_base.den); put_be16(pb, codec->width); put_be16(pb, codec->height); put_be16(pb, codec->gop_size); put_be32(pb, codec->pix_fmt); put_byte(pb, codec->qmin); put_byte(pb, codec->qmax); put_byte(pb, codec->max_qdiff); put_be16(pb, (int) (codec->qcompress * 10000.0)); put_be16(pb, (int) (codec->qblur * 10000.0)); put_be32(pb, codec->bit_rate_tolerance); put_strz(pb, codec->rc_eq ? codec->rc_eq : "tex^qComp"); put_be32(pb, codec->rc_max_rate); put_be32(pb, codec->rc_min_rate); put_be32(pb, codec->rc_buffer_size); put_be64(pb, av_dbl2int(codec->i_quant_factor)); put_be64(pb, av_dbl2int(codec->b_quant_factor)); put_be64(pb, av_dbl2int(codec->i_quant_offset)); put_be64(pb, av_dbl2int(codec->b_quant_offset)); put_be32(pb, codec->dct_algo); put_be32(pb, codec->strict_std_compliance); put_be32(pb, codec->max_b_frames); put_be32(pb, codec->luma_elim_threshold); put_be32(pb, codec->chroma_elim_threshold); put_be32(pb, codec->mpeg_quant); put_be32(pb, codec->intra_dc_precision); put_be32(pb, codec->me_method); put_be32(pb, codec->mb_decision); put_be32(pb, codec->nsse_weight); put_be32(pb, codec->frame_skip_cmp); put_be64(pb, av_dbl2int(codec->rc_buffer_aggressivity)); put_be32(pb, codec->codec_tag); put_byte(pb, codec->thread_count); put_be32(pb, codec->coder_type); put_be32(pb, codec->me_cmp); put_be32(pb, codec->partitions); put_be32(pb, codec->me_subpel_quality); put_be32(pb, codec->me_range); put_be32(pb, codec->keyint_min); put_be32(pb, codec->scenechange_threshold); put_be32(pb, codec->b_frame_strategy); put_be64(pb, av_dbl2int(codec->qcompress)); put_be64(pb, av_dbl2int(codec->qblur)); put_be32(pb, codec->max_qdiff); put_be32(pb, codec->refs); put_be32(pb, codec->directpred); break; case AVMEDIA_TYPE_AUDIO: put_be32(pb, codec->sample_rate); put_le16(pb, codec->channels); put_le16(pb, codec->frame_size); put_le16(pb, codec->sample_fmt); break; default: return -1; } if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) { put_be32(pb, codec->extradata_size); put_buffer(pb, codec->extradata, codec->extradata_size); } } /* flush until end of block reached */ while ((url_ftell(pb) % ffm->packet_size) != 0) put_byte(pb, 0); put_flush_packet(pb); /* init packet mux */ ffm->packet_ptr = ffm->packet; ffm->packet_end = ffm->packet + ffm->packet_size - FFM_HEADER_SIZE; assert(ffm->packet_end >= ffm->packet); ffm->frame_offset = 0; ffm->dts = 0; ffm->first_packet = 1; return 0; } static int ffm_write_packet(AVFormatContext *s, AVPacket *pkt) { int64_t dts; uint8_t header[FRAME_HEADER_SIZE+4]; int header_size = FRAME_HEADER_SIZE; dts = s->timestamp + pkt->dts; /* packet size & key_frame */ header[0] = pkt->stream_index; header[1] = 0; if (pkt->flags & AV_PKT_FLAG_KEY) header[1] |= FLAG_KEY_FRAME; AV_WB24(header+2, pkt->size); AV_WB24(header+5, pkt->duration); AV_WB64(header+8, s->timestamp + pkt->pts); if (pkt->pts != pkt->dts) { header[1] |= FLAG_DTS; AV_WB32(header+16, pkt->pts - pkt->dts); header_size += 4; } ffm_write_data(s, header, header_size, dts, 1); ffm_write_data(s, pkt->data, pkt->size, dts, 0); return 0; } static int ffm_write_trailer(AVFormatContext *s) { ByteIOContext *pb = s->pb; FFMContext *ffm = s->priv_data; /* flush packets */ if (ffm->packet_ptr > ffm->packet) flush_packet(s); put_flush_packet(pb); return 0; } AVOutputFormat ffm_muxer = { "ffm", NULL_IF_CONFIG_SMALL("FFM (FFserver live feed) format"), "", "ffm", sizeof(FFMContext), /* not really used */ CODEC_ID_MP2, CODEC_ID_MPEG1VIDEO, ffm_write_header, ffm_write_packet, ffm_write_trailer, };
123linslouis-android-video-cutter
jni/libavformat/ffmenc.c
C
asf20
8,044
# LOCAL_PATH is one of libavutil, libavcodec, libavformat, or libswscale #include $(LOCAL_PATH)/../config-$(TARGET_ARCH).mak include $(LOCAL_PATH)/../config.mak OBJS := OBJS-yes := MMX-OBJS-yes := include $(LOCAL_PATH)/Makefile # collect objects OBJS-$(HAVE_MMX) += $(MMX-OBJS-yes) OBJS += $(OBJS-yes) FFNAME := lib$(NAME) FFLIBS := $(foreach,NAME,$(FFLIBS),lib$(NAME)) FFCFLAGS = -DHAVE_AV_CONFIG_H -Wno-sign-compare -Wno-switch -Wno-pointer-sign FFCFLAGS += -DTARGET_CONFIG=\"config-$(TARGET_ARCH).h\" ALL_S_FILES := $(wildcard $(LOCAL_PATH)/$(TARGET_ARCH)/*.S) ALL_S_FILES := $(addprefix $(TARGET_ARCH)/, $(notdir $(ALL_S_FILES))) ifneq ($(ALL_S_FILES),) ALL_S_OBJS := $(patsubst %.S,%.o,$(ALL_S_FILES)) C_OBJS := $(filter-out $(ALL_S_OBJS),$(OBJS)) S_OBJS := $(filter $(ALL_S_OBJS),$(OBJS)) else C_OBJS := $(OBJS) S_OBJS := endif C_FILES := $(patsubst %.o,%.c,$(C_OBJS)) S_FILES := $(patsubst %.o,%.S,$(S_OBJS)) FFFILES := $(sort $(S_FILES)) $(sort $(C_FILES))
123linslouis-android-video-cutter
jni/av.mk
Makefile
asf20
973
/* * rational numbers * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * rational numbers * @author Michael Niedermayer <michaelni@gmx.at> */ #include <assert.h> //#include <math.h> #include <limits.h> #include "common.h" #include "mathematics.h" #include "rational.h" int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max){ AVRational a0={0,1}, a1={1,0}; int sign= (num<0) ^ (den<0); int64_t gcd= av_gcd(FFABS(num), FFABS(den)); if(gcd){ num = FFABS(num)/gcd; den = FFABS(den)/gcd; } if(num<=max && den<=max){ a1= (AVRational){num, den}; den=0; } while(den){ uint64_t x = num / den; int64_t next_den= num - den*x; int64_t a2n= x*a1.num + a0.num; int64_t a2d= x*a1.den + a0.den; if(a2n > max || a2d > max){ if(a1.num) x= (max - a0.num) / a1.num; if(a1.den) x= FFMIN(x, (max - a0.den) / a1.den); if (den*(2*x*a1.den + a0.den) > num*a1.den) a1 = (AVRational){x*a1.num + a0.num, x*a1.den + a0.den}; break; } a0= a1; a1= (AVRational){a2n, a2d}; num= den; den= next_den; } assert(av_gcd(a1.num, a1.den) <= 1U); *dst_num = sign ? -a1.num : a1.num; *dst_den = a1.den; return den==0; } AVRational av_mul_q(AVRational b, AVRational c){ av_reduce(&b.num, &b.den, b.num * (int64_t)c.num, b.den * (int64_t)c.den, INT_MAX); return b; } AVRational av_div_q(AVRational b, AVRational c){ return av_mul_q(b, (AVRational){c.den, c.num}); } AVRational av_add_q(AVRational b, AVRational c){ av_reduce(&b.num, &b.den, b.num * (int64_t)c.den + c.num * (int64_t)b.den, b.den * (int64_t)c.den, INT_MAX); return b; } AVRational av_sub_q(AVRational b, AVRational c){ return av_add_q(b, (AVRational){-c.num, c.den}); } AVRational av_d2q(double d, int max){ AVRational a; #define LOG2 0.69314718055994530941723212145817656807550013436025 int exponent= FFMAX( (int)(log(fabs(d) + 1e-20)/LOG2), 0); int64_t den= 1LL << (61 - exponent); if (isnan(d)) return (AVRational){0,0}; av_reduce(&a.num, &a.den, (int64_t)(d * den + 0.5), den, max); return a; } int av_nearer_q(AVRational q, AVRational q1, AVRational q2) { /* n/d is q, a/b is the median between q1 and q2 */ int64_t a = q1.num * (int64_t)q2.den + q2.num * (int64_t)q1.den; int64_t b = 2 * (int64_t)q1.den * q2.den; /* rnd_up(a*d/b) > n => a*d/b > n */ int64_t x_up = av_rescale_rnd(a, q.den, b, AV_ROUND_UP); /* rnd_down(a*d/b) < n => a*d/b < n */ int64_t x_down = av_rescale_rnd(a, q.den, b, AV_ROUND_DOWN); return ((x_up > q.num) - (x_down < q.num)) * av_cmp_q(q2, q1); } int av_find_nearest_q_idx(AVRational q, const AVRational* q_list) { int i, nearest_q_idx = 0; for(i=0; q_list[i].den; i++) if (av_nearer_q(q, q_list[i], q_list[nearest_q_idx]) > 0) nearest_q_idx = i; return nearest_q_idx; }
123linslouis-android-video-cutter
jni/libavutil/rational.c
C
asf20
3,820
/* * DES encryption/decryption * Copyright (c) 2007 Reimar Doeffinger * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include "avutil.h" #include "common.h" #include "intreadwrite.h" #include "des.h" typedef struct AVDES AVDES; #define T(a, b, c, d, e, f, g, h) 64-a,64-b,64-c,64-d,64-e,64-f,64-g,64-h static const uint8_t IP_shuffle[] = { T(58, 50, 42, 34, 26, 18, 10, 2), T(60, 52, 44, 36, 28, 20, 12, 4), T(62, 54, 46, 38, 30, 22, 14, 6), T(64, 56, 48, 40, 32, 24, 16, 8), T(57, 49, 41, 33, 25, 17, 9, 1), T(59, 51, 43, 35, 27, 19, 11, 3), T(61, 53, 45, 37, 29, 21, 13, 5), T(63, 55, 47, 39, 31, 23, 15, 7) }; #undef T #define T(a, b, c, d) 32-a,32-b,32-c,32-d static const uint8_t P_shuffle[] = { T(16, 7, 20, 21), T(29, 12, 28, 17), T( 1, 15, 23, 26), T( 5, 18, 31, 10), T( 2, 8, 24, 14), T(32, 27, 3, 9), T(19, 13, 30, 6), T(22, 11, 4, 25) }; #undef T #define T(a, b, c, d, e, f, g) 64-a,64-b,64-c,64-d,64-e,64-f,64-g static const uint8_t PC1_shuffle[] = { T(57, 49, 41, 33, 25, 17, 9), T( 1, 58, 50, 42, 34, 26, 18), T(10, 2, 59, 51, 43, 35, 27), T(19, 11, 3, 60, 52, 44, 36), T(63, 55, 47, 39, 31, 23, 15), T( 7, 62, 54, 46, 38, 30, 22), T(14, 6, 61, 53, 45, 37, 29), T(21, 13, 5, 28, 20, 12, 4) }; #undef T #define T(a, b, c, d, e, f) 56-a,56-b,56-c,56-d,56-e,56-f static const uint8_t PC2_shuffle[] = { T(14, 17, 11, 24, 1, 5), T( 3, 28, 15, 6, 21, 10), T(23, 19, 12, 4, 26, 8), T(16, 7, 27, 20, 13, 2), T(41, 52, 31, 37, 47, 55), T(30, 40, 51, 45, 33, 48), T(44, 49, 39, 56, 34, 53), T(46, 42, 50, 36, 29, 32) }; #undef T #if CONFIG_SMALL static const uint8_t S_boxes[8][32] = { { 0x0e, 0xf4, 0x7d, 0x41, 0xe2, 0x2f, 0xdb, 0x18, 0xa3, 0x6a, 0xc6, 0xbc, 0x95, 0x59, 0x30, 0x87, 0xf4, 0xc1, 0x8e, 0x28, 0x4d, 0x96, 0x12, 0x7b, 0x5f, 0xbc, 0x39, 0xe7, 0xa3, 0x0a, 0x65, 0xd0, }, { 0x3f, 0xd1, 0x48, 0x7e, 0xf6, 0x2b, 0x83, 0xe4, 0xc9, 0x07, 0x12, 0xad, 0x6c, 0x90, 0xb5, 0x5a, 0xd0, 0x8e, 0xa7, 0x1b, 0x3a, 0xf4, 0x4d, 0x21, 0xb5, 0x68, 0x7c, 0xc6, 0x09, 0x53, 0xe2, 0x9f, }, { 0xda, 0x70, 0x09, 0x9e, 0x36, 0x43, 0x6f, 0xa5, 0x21, 0x8d, 0x5c, 0xe7, 0xcb, 0xb4, 0xf2, 0x18, 0x1d, 0xa6, 0xd4, 0x09, 0x68, 0x9f, 0x83, 0x70, 0x4b, 0xf1, 0xe2, 0x3c, 0xb5, 0x5a, 0x2e, 0xc7, }, { 0xd7, 0x8d, 0xbe, 0x53, 0x60, 0xf6, 0x09, 0x3a, 0x41, 0x72, 0x28, 0xc5, 0x1b, 0xac, 0xe4, 0x9f, 0x3a, 0xf6, 0x09, 0x60, 0xac, 0x1b, 0xd7, 0x8d, 0x9f, 0x41, 0x53, 0xbe, 0xc5, 0x72, 0x28, 0xe4, }, { 0xe2, 0xbc, 0x24, 0xc1, 0x47, 0x7a, 0xdb, 0x16, 0x58, 0x05, 0xf3, 0xaf, 0x3d, 0x90, 0x8e, 0x69, 0xb4, 0x82, 0xc1, 0x7b, 0x1a, 0xed, 0x27, 0xd8, 0x6f, 0xf9, 0x0c, 0x95, 0xa6, 0x43, 0x50, 0x3e, }, { 0xac, 0xf1, 0x4a, 0x2f, 0x79, 0xc2, 0x96, 0x58, 0x60, 0x1d, 0xd3, 0xe4, 0x0e, 0xb7, 0x35, 0x8b, 0x49, 0x3e, 0x2f, 0xc5, 0x92, 0x58, 0xfc, 0xa3, 0xb7, 0xe0, 0x14, 0x7a, 0x61, 0x0d, 0x8b, 0xd6, }, { 0xd4, 0x0b, 0xb2, 0x7e, 0x4f, 0x90, 0x18, 0xad, 0xe3, 0x3c, 0x59, 0xc7, 0x25, 0xfa, 0x86, 0x61, 0x61, 0xb4, 0xdb, 0x8d, 0x1c, 0x43, 0xa7, 0x7e, 0x9a, 0x5f, 0x06, 0xf8, 0xe0, 0x25, 0x39, 0xc2, }, { 0x1d, 0xf2, 0xd8, 0x84, 0xa6, 0x3f, 0x7b, 0x41, 0xca, 0x59, 0x63, 0xbe, 0x05, 0xe0, 0x9c, 0x27, 0x27, 0x1b, 0xe4, 0x71, 0x49, 0xac, 0x8e, 0xd2, 0xf0, 0xc6, 0x9a, 0x0d, 0x3f, 0x53, 0x65, 0xb8, } }; #else /** * This table contains the results of applying both the S-box and P-shuffle. * It can be regenerated by compiling this file with -DCONFIG_SMALL -DTEST -DGENTABLES */ static const uint32_t S_boxes_P_shuffle[8][64] = { { 0x00808200, 0x00000000, 0x00008000, 0x00808202, 0x00808002, 0x00008202, 0x00000002, 0x00008000, 0x00000200, 0x00808200, 0x00808202, 0x00000200, 0x00800202, 0x00808002, 0x00800000, 0x00000002, 0x00000202, 0x00800200, 0x00800200, 0x00008200, 0x00008200, 0x00808000, 0x00808000, 0x00800202, 0x00008002, 0x00800002, 0x00800002, 0x00008002, 0x00000000, 0x00000202, 0x00008202, 0x00800000, 0x00008000, 0x00808202, 0x00000002, 0x00808000, 0x00808200, 0x00800000, 0x00800000, 0x00000200, 0x00808002, 0x00008000, 0x00008200, 0x00800002, 0x00000200, 0x00000002, 0x00800202, 0x00008202, 0x00808202, 0x00008002, 0x00808000, 0x00800202, 0x00800002, 0x00000202, 0x00008202, 0x00808200, 0x00000202, 0x00800200, 0x00800200, 0x00000000, 0x00008002, 0x00008200, 0x00000000, 0x00808002, }, { 0x40084010, 0x40004000, 0x00004000, 0x00084010, 0x00080000, 0x00000010, 0x40080010, 0x40004010, 0x40000010, 0x40084010, 0x40084000, 0x40000000, 0x40004000, 0x00080000, 0x00000010, 0x40080010, 0x00084000, 0x00080010, 0x40004010, 0x00000000, 0x40000000, 0x00004000, 0x00084010, 0x40080000, 0x00080010, 0x40000010, 0x00000000, 0x00084000, 0x00004010, 0x40084000, 0x40080000, 0x00004010, 0x00000000, 0x00084010, 0x40080010, 0x00080000, 0x40004010, 0x40080000, 0x40084000, 0x00004000, 0x40080000, 0x40004000, 0x00000010, 0x40084010, 0x00084010, 0x00000010, 0x00004000, 0x40000000, 0x00004010, 0x40084000, 0x00080000, 0x40000010, 0x00080010, 0x40004010, 0x40000010, 0x00080010, 0x00084000, 0x00000000, 0x40004000, 0x00004010, 0x40000000, 0x40080010, 0x40084010, 0x00084000, }, { 0x00000104, 0x04010100, 0x00000000, 0x04010004, 0x04000100, 0x00000000, 0x00010104, 0x04000100, 0x00010004, 0x04000004, 0x04000004, 0x00010000, 0x04010104, 0x00010004, 0x04010000, 0x00000104, 0x04000000, 0x00000004, 0x04010100, 0x00000100, 0x00010100, 0x04010000, 0x04010004, 0x00010104, 0x04000104, 0x00010100, 0x00010000, 0x04000104, 0x00000004, 0x04010104, 0x00000100, 0x04000000, 0x04010100, 0x04000000, 0x00010004, 0x00000104, 0x00010000, 0x04010100, 0x04000100, 0x00000000, 0x00000100, 0x00010004, 0x04010104, 0x04000100, 0x04000004, 0x00000100, 0x00000000, 0x04010004, 0x04000104, 0x00010000, 0x04000000, 0x04010104, 0x00000004, 0x00010104, 0x00010100, 0x04000004, 0x04010000, 0x04000104, 0x00000104, 0x04010000, 0x00010104, 0x00000004, 0x04010004, 0x00010100, }, { 0x80401000, 0x80001040, 0x80001040, 0x00000040, 0x00401040, 0x80400040, 0x80400000, 0x80001000, 0x00000000, 0x00401000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00400040, 0x80400000, 0x80000000, 0x00001000, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x80001000, 0x00001040, 0x80400040, 0x80000000, 0x00001040, 0x00400040, 0x00001000, 0x00401040, 0x80401040, 0x80000040, 0x00400040, 0x80400000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00000000, 0x00401000, 0x00001040, 0x00400040, 0x80400040, 0x80000000, 0x80401000, 0x80001040, 0x80001040, 0x00000040, 0x80401040, 0x80000040, 0x80000000, 0x00001000, 0x80400000, 0x80001000, 0x00401040, 0x80400040, 0x80001000, 0x00001040, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x00001000, 0x00401040, }, { 0x00000080, 0x01040080, 0x01040000, 0x21000080, 0x00040000, 0x00000080, 0x20000000, 0x01040000, 0x20040080, 0x00040000, 0x01000080, 0x20040080, 0x21000080, 0x21040000, 0x00040080, 0x20000000, 0x01000000, 0x20040000, 0x20040000, 0x00000000, 0x20000080, 0x21040080, 0x21040080, 0x01000080, 0x21040000, 0x20000080, 0x00000000, 0x21000000, 0x01040080, 0x01000000, 0x21000000, 0x00040080, 0x00040000, 0x21000080, 0x00000080, 0x01000000, 0x20000000, 0x01040000, 0x21000080, 0x20040080, 0x01000080, 0x20000000, 0x21040000, 0x01040080, 0x20040080, 0x00000080, 0x01000000, 0x21040000, 0x21040080, 0x00040080, 0x21000000, 0x21040080, 0x01040000, 0x00000000, 0x20040000, 0x21000000, 0x00040080, 0x01000080, 0x20000080, 0x00040000, 0x00000000, 0x20040000, 0x01040080, 0x20000080, }, { 0x10000008, 0x10200000, 0x00002000, 0x10202008, 0x10200000, 0x00000008, 0x10202008, 0x00200000, 0x10002000, 0x00202008, 0x00200000, 0x10000008, 0x00200008, 0x10002000, 0x10000000, 0x00002008, 0x00000000, 0x00200008, 0x10002008, 0x00002000, 0x00202000, 0x10002008, 0x00000008, 0x10200008, 0x10200008, 0x00000000, 0x00202008, 0x10202000, 0x00002008, 0x00202000, 0x10202000, 0x10000000, 0x10002000, 0x00000008, 0x10200008, 0x00202000, 0x10202008, 0x00200000, 0x00002008, 0x10000008, 0x00200000, 0x10002000, 0x10000000, 0x00002008, 0x10000008, 0x10202008, 0x00202000, 0x10200000, 0x00202008, 0x10202000, 0x00000000, 0x10200008, 0x00000008, 0x00002000, 0x10200000, 0x00202008, 0x00002000, 0x00200008, 0x10002008, 0x00000000, 0x10202000, 0x10000000, 0x00200008, 0x10002008, }, { 0x00100000, 0x02100001, 0x02000401, 0x00000000, 0x00000400, 0x02000401, 0x00100401, 0x02100400, 0x02100401, 0x00100000, 0x00000000, 0x02000001, 0x00000001, 0x02000000, 0x02100001, 0x00000401, 0x02000400, 0x00100401, 0x00100001, 0x02000400, 0x02000001, 0x02100000, 0x02100400, 0x00100001, 0x02100000, 0x00000400, 0x00000401, 0x02100401, 0x00100400, 0x00000001, 0x02000000, 0x00100400, 0x02000000, 0x00100400, 0x00100000, 0x02000401, 0x02000401, 0x02100001, 0x02100001, 0x00000001, 0x00100001, 0x02000000, 0x02000400, 0x00100000, 0x02100400, 0x00000401, 0x00100401, 0x02100400, 0x00000401, 0x02000001, 0x02100401, 0x02100000, 0x00100400, 0x00000000, 0x00000001, 0x02100401, 0x00000000, 0x00100401, 0x02100000, 0x00000400, 0x02000001, 0x02000400, 0x00000400, 0x00100001, }, { 0x08000820, 0x00000800, 0x00020000, 0x08020820, 0x08000000, 0x08000820, 0x00000020, 0x08000000, 0x00020020, 0x08020000, 0x08020820, 0x00020800, 0x08020800, 0x00020820, 0x00000800, 0x00000020, 0x08020000, 0x08000020, 0x08000800, 0x00000820, 0x00020800, 0x00020020, 0x08020020, 0x08020800, 0x00000820, 0x00000000, 0x00000000, 0x08020020, 0x08000020, 0x08000800, 0x00020820, 0x00020000, 0x00020820, 0x00020000, 0x08020800, 0x00000800, 0x00000020, 0x08020020, 0x00000800, 0x00020820, 0x08000800, 0x00000020, 0x08000020, 0x08020000, 0x08020020, 0x08000000, 0x00020000, 0x08000820, 0x00000000, 0x08020820, 0x00020020, 0x08000020, 0x08020000, 0x08000800, 0x08000820, 0x00000000, 0x08020820, 0x00020800, 0x00020800, 0x00000820, 0x00000820, 0x00020020, 0x08000000, 0x08020800, }, }; #endif static uint64_t shuffle(uint64_t in, const uint8_t *shuffle, int shuffle_len) { int i; uint64_t res = 0; for (i = 0; i < shuffle_len; i++) res += res + ((in >> *shuffle++) & 1); return res; } static uint64_t shuffle_inv(uint64_t in, const uint8_t *shuffle, int shuffle_len) { int i; uint64_t res = 0; shuffle += shuffle_len - 1; for (i = 0; i < shuffle_len; i++) { res |= (in & 1) << *shuffle--; in >>= 1; } return res; } static uint32_t f_func(uint32_t r, uint64_t k) { int i; uint32_t out = 0; // rotate to get first part of E-shuffle in the lowest 6 bits r = (r << 1) | (r >> 31); // apply S-boxes, those compress the data again from 8 * 6 to 8 * 4 bits for (i = 7; i >= 0; i--) { uint8_t tmp = (r ^ k) & 0x3f; #if CONFIG_SMALL uint8_t v = S_boxes[i][tmp >> 1]; if (tmp & 1) v >>= 4; out = (out >> 4) | (v << 28); #else out |= S_boxes_P_shuffle[i][tmp]; #endif // get next 6 bits of E-shuffle and round key k into the lowest bits r = (r >> 4) | (r << 28); k >>= 6; } #if CONFIG_SMALL out = shuffle(out, P_shuffle, sizeof(P_shuffle)); #endif return out; } /** * \brief rotate the two halves of the expanded 56 bit key each 1 bit left * * Note: the specification calls this "shift", so I kept it although * it is confusing. */ static uint64_t key_shift_left(uint64_t CDn) { uint64_t carries = (CDn >> 27) & 0x10000001; CDn <<= 1; CDn &= ~0x10000001; CDn |= carries; return CDn; } static void gen_roundkeys(uint64_t K[16], uint64_t key) { int i; // discard parity bits from key and shuffle it into C and D parts uint64_t CDn = shuffle(key, PC1_shuffle, sizeof(PC1_shuffle)); // generate round keys for (i = 0; i < 16; i++) { CDn = key_shift_left(CDn); if (i > 1 && i != 8 && i != 15) CDn = key_shift_left(CDn); K[i] = shuffle(CDn, PC2_shuffle, sizeof(PC2_shuffle)); } } static uint64_t des_encdec(uint64_t in, uint64_t K[16], int decrypt) { int i; // used to apply round keys in reverse order for decryption decrypt = decrypt ? 15 : 0; // shuffle irrelevant to security but to ease hardware implementations in = shuffle(in, IP_shuffle, sizeof(IP_shuffle)); for (i = 0; i < 16; i++) { uint32_t f_res; f_res = f_func(in, K[decrypt ^ i]); in = (in << 32) | (in >> 32); in ^= f_res; } in = (in << 32) | (in >> 32); // reverse shuffle used to ease hardware implementations in = shuffle_inv(in, IP_shuffle, sizeof(IP_shuffle)); return in; } int av_des_init(AVDES *d, const uint8_t *key, int key_bits, int decrypt) { if (key_bits != 64 && key_bits != 192) return -1; d->triple_des = key_bits > 64; gen_roundkeys(d->round_keys[0], AV_RB64(key)); if (d->triple_des) { gen_roundkeys(d->round_keys[1], AV_RB64(key + 8)); gen_roundkeys(d->round_keys[2], AV_RB64(key + 16)); } return 0; } void av_des_crypt(AVDES *d, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt) { uint64_t iv_val = iv ? be2me_64(*(uint64_t *)iv) : 0; while (count-- > 0) { uint64_t dst_val; uint64_t src_val = src ? be2me_64(*(const uint64_t *)src) : 0; if (decrypt) { uint64_t tmp = src_val; if (d->triple_des) { src_val = des_encdec(src_val, d->round_keys[2], 1); src_val = des_encdec(src_val, d->round_keys[1], 0); } dst_val = des_encdec(src_val, d->round_keys[0], 1) ^ iv_val; iv_val = iv ? tmp : 0; } else { dst_val = des_encdec(src_val ^ iv_val, d->round_keys[0], 0); if (d->triple_des) { dst_val = des_encdec(dst_val, d->round_keys[1], 1); dst_val = des_encdec(dst_val, d->round_keys[2], 0); } iv_val = iv ? dst_val : 0; } *(uint64_t *)dst = be2me_64(dst_val); src += 8; dst += 8; } if (iv) *(uint64_t *)iv = be2me_64(iv_val); } #ifdef TEST #undef printf #undef rand #undef srand #include <stdlib.h> #include <stdio.h> #include <sys/time.h> static uint64_t rand64(void) { uint64_t r = rand(); r = (r << 32) | rand(); return r; } static const uint8_t test_key[] = {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}; static const DECLARE_ALIGNED(8, uint8_t, plain)[] = {0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}; static const DECLARE_ALIGNED(8, uint8_t, crypt)[] = {0x4a, 0xb6, 0x5b, 0x3d, 0x4b, 0x06, 0x15, 0x18}; static DECLARE_ALIGNED(8, uint8_t, tmp)[8]; static DECLARE_ALIGNED(8, uint8_t, large_buffer)[10002][8]; static const uint8_t cbc_key[] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23 }; static int run_test(int cbc, int decrypt) { AVDES d; int delay = cbc && !decrypt ? 2 : 1; uint64_t res; AV_WB64(large_buffer[0], 0x4e6f772069732074ULL); AV_WB64(large_buffer[1], 0x1234567890abcdefULL); AV_WB64(tmp, 0x1234567890abcdefULL); av_des_init(&d, cbc_key, 192, decrypt); av_des_crypt(&d, large_buffer[delay], large_buffer[0], 10000, cbc ? tmp : NULL, decrypt); res = AV_RB64(large_buffer[9999 + delay]); if (cbc) { if (decrypt) return res == 0xc5cecf63ecec514cULL; else return res == 0xcb191f85d1ed8439ULL; } else { if (decrypt) return res == 0x8325397644091a0aULL; else return res == 0xdd17e8b8b437d232ULL; } } int main(void) { AVDES d; int i; #ifdef GENTABLES int j; #endif struct timeval tv; uint64_t key[3]; uint64_t data; uint64_t ct; uint64_t roundkeys[16]; gettimeofday(&tv, NULL); srand(tv.tv_sec * 1000 * 1000 + tv.tv_usec); key[0] = AV_RB64(test_key); data = AV_RB64(plain); gen_roundkeys(roundkeys, key[0]); if (des_encdec(data, roundkeys, 0) != AV_RB64(crypt)) { printf("Test 1 failed\n"); return 1; } av_des_init(&d, test_key, 64, 0); av_des_crypt(&d, tmp, plain, 1, NULL, 0); if (memcmp(tmp, crypt, sizeof(crypt))) { printf("Public API decryption failed\n"); return 1; } if (!run_test(0, 0) || !run_test(0, 1) || !run_test(1, 0) || !run_test(1, 1)) { printf("Partial Monte-Carlo test failed\n"); return 1; } for (i = 0; i < 1000000; i++) { key[0] = rand64(); key[1] = rand64(); key[2] = rand64(); data = rand64(); av_des_init(&d, key, 192, 0); av_des_crypt(&d, &ct, &data, 1, NULL, 0); av_des_init(&d, key, 192, 1); av_des_crypt(&d, &ct, &ct, 1, NULL, 1); if (ct != data) { printf("Test 2 failed\n"); return 1; } } #ifdef GENTABLES printf("static const uint32_t S_boxes_P_shuffle[8][64] = {\n"); for (i = 0; i < 8; i++) { printf(" {"); for (j = 0; j < 64; j++) { uint32_t v = S_boxes[i][j >> 1]; v = j & 1 ? v >> 4 : v & 0xf; v <<= 28 - 4 * i; v = shuffle(v, P_shuffle, sizeof(P_shuffle)); printf((j & 7) == 0 ? "\n " : " "); printf("0x%08X,", v); } printf("\n },\n"); } printf("};\n"); #endif return 0; } #endif
123linslouis-android-video-cutter
jni/libavutil/des.c
C
asf20
18,400
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_CRC_H #define AVUTIL_CRC_H #include <stdint.h> #include <stddef.h> #include "attributes.h" typedef uint32_t AVCRC; typedef enum { AV_CRC_8_ATM, AV_CRC_16_ANSI, AV_CRC_16_CCITT, AV_CRC_32_IEEE, AV_CRC_32_IEEE_LE, /*< reversed bitorder version of AV_CRC_32_IEEE */ AV_CRC_MAX, /*< Not part of public API! Do not use outside libavutil. */ }AVCRCId; int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size); const AVCRC *av_crc_get_table(AVCRCId crc_id); uint32_t av_crc(const AVCRC *ctx, uint32_t start_crc, const uint8_t *buffer, size_t length) av_pure; #endif /* AVUTIL_CRC_H */
123linslouis-android-video-cutter
jni/libavutil/crc.h
C
asf20
1,478
/* * Copyright (c) 2006 Ryan Martell. (rdm4@martellventures.com) * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_BASE64_H #define AVUTIL_BASE64_H #include <stdint.h> /** * Decodes the base64-encoded string in in and puts the decoded * data in out. * * @param out_size size in bytes of the out buffer, it should be at * least 3/4 of the length of in * @return the number of bytes written, or a negative value in case of * error */ int av_base64_decode(uint8_t *out, const char *in, int out_size); /** * Encodes in base64 the data in in and puts the resulting string * in out. * * @param out_size size in bytes of the out string, it should be at * least ((in_size + 2) / 3) * 4 + 1 * @param in_size size in bytes of the in buffer * @return the string containing the encoded data, or NULL in case of * error */ char *av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size); #endif /* AVUTIL_BASE64_H */
123linslouis-android-video-cutter
jni/libavutil/base64.h
C
asf20
1,671
/* * Copyright (C) 2007 Michael Niedermayer <michaelni@gmx.at> * Copyright (C) 2009 Konstantin Shishkov * based on public domain SHA-1 code by Steve Reid <steve@edmweb.com> * and on BSD-licensed SHA-2 code by Aaron D. Gifford * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <string.h> #include "avutil.h" #include "bswap.h" #include "sha.h" #include "sha1.h" #include "intreadwrite.h" /** hash context */ typedef struct AVSHA { uint8_t digest_len; ///< digest length in 32-bit words uint64_t count; ///< number of bytes in buffer uint8_t buffer[64]; ///< 512-bit buffer of input values used in hash updating uint32_t state[8]; ///< current hash value /** function used to update hash for 512-bit input block */ void (*transform)(uint32_t *state, const uint8_t buffer[64]); } AVSHA; const int av_sha_size = sizeof(AVSHA); #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ #define blk0(i) (block[i] = be2me_32(((const uint32_t*)buffer)[i])) #define blk(i) (block[i] = rol(block[i-3] ^ block[i-8] ^ block[i-14] ^ block[i-16], 1)) #define R0(v,w,x,y,z,i) z += ((w&(x^y))^y) + blk0(i) + 0x5A827999 + rol(v, 5); w = rol(w, 30); #define R1(v,w,x,y,z,i) z += ((w&(x^y))^y) + blk (i) + 0x5A827999 + rol(v, 5); w = rol(w, 30); #define R2(v,w,x,y,z,i) z += ( w^x ^y) + blk (i) + 0x6ED9EBA1 + rol(v, 5); w = rol(w, 30); #define R3(v,w,x,y,z,i) z += (((w|x)&y)|(w&x)) + blk (i) + 0x8F1BBCDC + rol(v, 5); w = rol(w, 30); #define R4(v,w,x,y,z,i) z += ( w^x ^y) + blk (i) + 0xCA62C1D6 + rol(v, 5); w = rol(w, 30); /* Hash a single 512-bit block. This is the core of the algorithm. */ static void sha1_transform(uint32_t state[5], const uint8_t buffer[64]) { uint32_t block[80]; unsigned int i, a, b, c, d, e; a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; #if CONFIG_SMALL for (i = 0; i < 80; i++) { int t; if (i < 16) t = be2me_32(((uint32_t*)buffer)[i]); else t = rol(block[i-3] ^ block[i-8] ^ block[i-14] ^ block[i-16], 1); block[i] = t; t += e + rol(a, 5); if (i < 40) { if (i < 20) t += ((b&(c^d))^d) + 0x5A827999; else t += ( b^c ^d) + 0x6ED9EBA1; } else { if (i < 60) t += (((b|c)&d)|(b&c)) + 0x8F1BBCDC; else t += ( b^c ^d) + 0xCA62C1D6; } e = d; d = c; c = rol(b, 30); b = a; a = t; } #else for (i = 0; i < 15; i += 5) { R0(a, b, c, d, e, 0 + i); R0(e, a, b, c, d, 1 + i); R0(d, e, a, b, c, 2 + i); R0(c, d, e, a, b, 3 + i); R0(b, c, d, e, a, 4 + i); } R0(a, b, c, d, e, 15); R1(e, a, b, c, d, 16); R1(d, e, a, b, c, 17); R1(c, d, e, a, b, 18); R1(b, c, d, e, a, 19); for (i = 20; i < 40; i += 5) { R2(a, b, c, d, e, 0 + i); R2(e, a, b, c, d, 1 + i); R2(d, e, a, b, c, 2 + i); R2(c, d, e, a, b, 3 + i); R2(b, c, d, e, a, 4 + i); } for (; i < 60; i += 5) { R3(a, b, c, d, e, 0 + i); R3(e, a, b, c, d, 1 + i); R3(d, e, a, b, c, 2 + i); R3(c, d, e, a, b, 3 + i); R3(b, c, d, e, a, 4 + i); } for (; i < 80; i += 5) { R4(a, b, c, d, e, 0 + i); R4(e, a, b, c, d, 1 + i); R4(d, e, a, b, c, 2 + i); R4(c, d, e, a, b, 3 + i); R4(b, c, d, e, a, 4 + i); } #endif state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; } static const uint32_t K256[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; #define Ch(x,y,z) (((x) & ((y) ^ (z))) ^ (z)) #define Maj(x,y,z) ((((x) | (y)) & (z)) | ((x) & (y))) #define Sigma0_256(x) (rol((x), 30) ^ rol((x), 19) ^ rol((x), 10)) #define Sigma1_256(x) (rol((x), 26) ^ rol((x), 21) ^ rol((x), 7)) #define sigma0_256(x) (rol((x), 25) ^ rol((x), 14) ^ ((x) >> 3)) #define sigma1_256(x) (rol((x), 15) ^ rol((x), 13) ^ ((x) >> 10)) #undef blk #define blk(i) (block[i] = block[i - 16] + sigma0_256(block[i - 15]) + \ sigma1_256(block[i - 2]) + block[i - 7]) #define ROUND256(a,b,c,d,e,f,g,h) \ T1 += (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[i]; \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ i++ #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ T1 = blk0(i); \ ROUND256(a,b,c,d,e,f,g,h) #define ROUND256_16_TO_63(a,b,c,d,e,f,g,h) \ T1 = blk(i); \ ROUND256(a,b,c,d,e,f,g,h) static void sha256_transform(uint32_t *state, const uint8_t buffer[64]) { unsigned int i, a, b, c, d, e, f, g, h; uint32_t block[64]; uint32_t T1, av_unused(T2); a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; f = state[5]; g = state[6]; h = state[7]; #if CONFIG_SMALL for (i = 0; i < 64; i++) { if (i < 16) T1 = blk0(i); else T1 = blk(i); T1 += h + Sigma1_256(e) + Ch(e, f, g) + K256[i]; T2 = Sigma0_256(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } #else for (i = 0; i < 16;) { ROUND256_0_TO_15(a, b, c, d, e, f, g, h); ROUND256_0_TO_15(h, a, b, c, d, e, f, g); ROUND256_0_TO_15(g, h, a, b, c, d, e, f); ROUND256_0_TO_15(f, g, h, a, b, c, d, e); ROUND256_0_TO_15(e, f, g, h, a, b, c, d); ROUND256_0_TO_15(d, e, f, g, h, a, b, c); ROUND256_0_TO_15(c, d, e, f, g, h, a, b); ROUND256_0_TO_15(b, c, d, e, f, g, h, a); } for (; i < 64;) { ROUND256_16_TO_63(a, b, c, d, e, f, g, h); ROUND256_16_TO_63(h, a, b, c, d, e, f, g); ROUND256_16_TO_63(g, h, a, b, c, d, e, f); ROUND256_16_TO_63(f, g, h, a, b, c, d, e); ROUND256_16_TO_63(e, f, g, h, a, b, c, d); ROUND256_16_TO_63(d, e, f, g, h, a, b, c); ROUND256_16_TO_63(c, d, e, f, g, h, a, b); ROUND256_16_TO_63(b, c, d, e, f, g, h, a); } #endif state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; state[5] += f; state[6] += g; state[7] += h; } int av_sha_init(AVSHA* ctx, int bits) { ctx->digest_len = bits >> 5; switch (bits) { case 160: // SHA-1 ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; ctx->state[4] = 0xC3D2E1F0; ctx->transform = sha1_transform; break; case 224: // SHA-224 ctx->state[0] = 0xC1059ED8; ctx->state[1] = 0x367CD507; ctx->state[2] = 0x3070DD17; ctx->state[3] = 0xF70E5939; ctx->state[4] = 0xFFC00B31; ctx->state[5] = 0x68581511; ctx->state[6] = 0x64F98FA7; ctx->state[7] = 0xBEFA4FA4; ctx->transform = sha256_transform; break; case 256: // SHA-256 ctx->state[0] = 0x6A09E667; ctx->state[1] = 0xBB67AE85; ctx->state[2] = 0x3C6EF372; ctx->state[3] = 0xA54FF53A; ctx->state[4] = 0x510E527F; ctx->state[5] = 0x9B05688C; ctx->state[6] = 0x1F83D9AB; ctx->state[7] = 0x5BE0CD19; ctx->transform = sha256_transform; break; default: return -1; } ctx->count = 0; return 0; } void av_sha_update(AVSHA* ctx, const uint8_t* data, unsigned int len) { unsigned int i, j; j = ctx->count & 63; ctx->count += len; #if CONFIG_SMALL for (i = 0; i < len; i++) { ctx->buffer[j++] = data[i]; if (64 == j) { ctx->transform(ctx->state, ctx->buffer); j = 0; } } #else if ((j + len) > 63) { memcpy(&ctx->buffer[j], data, (i = 64 - j)); ctx->transform(ctx->state, ctx->buffer); for (; i + 63 < len; i += 64) ctx->transform(ctx->state, &data[i]); j = 0; } else i = 0; memcpy(&ctx->buffer[j], &data[i], len - i); #endif } void av_sha_final(AVSHA* ctx, uint8_t *digest) { int i; uint64_t finalcount = be2me_64(ctx->count << 3); av_sha_update(ctx, "\200", 1); while ((ctx->count & 63) != 56) av_sha_update(ctx, "", 1); av_sha_update(ctx, (uint8_t *)&finalcount, 8); /* Should cause a transform() */ for (i = 0; i < ctx->digest_len; i++) AV_WB32(digest + i*4, ctx->state[i]); } #if LIBAVUTIL_VERSION_MAJOR < 51 struct AVSHA1 { AVSHA sha; }; const int av_sha1_size = sizeof(struct AVSHA1); void av_sha1_init(struct AVSHA1* context) { av_sha_init(&context->sha, 160); } void av_sha1_update(struct AVSHA1* context, const uint8_t* data, unsigned int len) { av_sha_update(&context->sha, data, len); } void av_sha1_final(struct AVSHA1* context, uint8_t digest[20]) { av_sha_final(&context->sha, digest); } #endif #ifdef TEST #include <stdio.h> #undef printf int main(void) { int i, j, k; AVSHA ctx; unsigned char digest[32]; const int lengths[3] = { 160, 224, 256 }; for (j = 0; j < 3; j++) { printf("Testing SHA-%d\n", lengths[j]); for (k = 0; k < 3; k++) { av_sha_init(&ctx, lengths[j]); if (k == 0) av_sha_update(&ctx, "abc", 3); else if (k == 1) av_sha_update(&ctx, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 56); else for (i = 0; i < 1000*1000; i++) av_sha_update(&ctx, "a", 1); av_sha_final(&ctx, digest); for (i = 0; i < lengths[j] >> 3; i++) printf("%02X", digest[i]); putchar('\n'); } switch (j) { case 0: //test vectors (from FIPS PUB 180-1) printf("A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D\n" "84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1\n" "34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F\n"); break; case 1: //test vectors (from FIPS PUB 180-2 Appendix A) printf("23097d22 3405d822 8642a477 bda255b3 2aadbce4 bda0b3f7 e36c9da7\n" "75388b16 512776cc 5dba5da1 fd890150 b0c6455c b4f58b19 52522525\n" "20794655 980c91d8 bbb4c1ea 97618a4b f03f4258 1948b2ee 4ee7ad67\n"); break; case 2: //test vectors (from FIPS PUB 180-2) printf("ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad\n" "248d6a61 d20638b8 e5c02693 0c3e6039 a33ce459 64ff2167 f6ecedd4 19db06c1\n" "cdc76e5c 9914fb92 81a1c7e2 84d73e67 f1809a48 a497200e 046d39cc c7112cd0\n"); break; } } return 0; } #endif
123linslouis-android-video-cutter
jni/libavutil/sha.c
C
asf20
12,541
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * byte swapping routines */ #ifndef AVUTIL_SH4_BSWAP_H #define AVUTIL_SH4_BSWAP_H #include <stdint.h> #include "config.h" #include "libavutil/attributes.h" #define bswap_16 bswap_16 static av_always_inline av_const uint16_t bswap_16(uint16_t x) { __asm__("swap.b %0,%0" : "+r"(x)); return x; } #define bswap_32 bswap_32 static av_always_inline av_const uint32_t bswap_32(uint32_t x) { __asm__("swap.b %0,%0\n" "swap.w %0,%0\n" "swap.b %0,%0\n" : "+r"(x)); return x; } #endif /* AVUTIL_SH4_BSWAP_H */
123linslouis-android-video-cutter
jni/libavutil/sh4/bswap.h
C
asf20
1,336
/* * Copyright (C) 2006 Michael Niedermayer (michaelni@gmx.at) * Copyright (C) 2003-2005 by Christopher R. Hertel (crh@ubiqx.mn.org) * * References: * IETF RFC 1321: The MD5 Message-Digest Algorithm * Ron Rivest. IETF, April, 1992 * * based on http://ubiqx.org/libcifs/source/Auth/MD5.c * from Christopher R. Hertel (crh@ubiqx.mn.org) * Simplified, cleaned and IMO redundant comments removed by michael. * * If you use gcc, then version 4.1 or later and -fomit-frame-pointer is * strongly recommended. * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <string.h> #include "bswap.h" #include "md5.h" typedef struct AVMD5{ uint64_t len; uint8_t block[64]; uint32_t ABCD[4]; } AVMD5; const int av_md5_size= sizeof(AVMD5); static const uint8_t S[4][4] = { { 7, 12, 17, 22 }, /* round 1 */ { 5, 9, 14, 20 }, /* round 2 */ { 4, 11, 16, 23 }, /* round 3 */ { 6, 10, 15, 21 } /* round 4 */ }; static const uint32_t T[64] = { // T[i]= fabs(sin(i+1)<<32) 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, /* round 1 */ 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, /* round 2 */ 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, /* round 3 */ 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, /* round 4 */ 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, }; #define CORE(i, a, b, c, d) \ t = S[i>>4][i&3];\ a += T[i];\ \ if(i<32){\ if(i<16) a += (d ^ (b&(c^d))) + X[ i &15 ];\ else a += (c ^ (d&(c^b))) + X[ (1+5*i)&15 ];\ }else{\ if(i<48) a += (b^c^d) + X[ (5+3*i)&15 ];\ else a += (c^(b|~d)) + X[ ( 7*i)&15 ];\ }\ a = b + (( a << t ) | ( a >> (32 - t) )); static void body(uint32_t ABCD[4], uint32_t X[16]){ int t; int i av_unused; unsigned int a= ABCD[3]; unsigned int b= ABCD[2]; unsigned int c= ABCD[1]; unsigned int d= ABCD[0]; #if HAVE_BIGENDIAN for(i=0; i<16; i++) X[i]= bswap_32(X[i]); #endif #if CONFIG_SMALL for( i = 0; i < 64; i++ ){ CORE(i,a,b,c,d) t=d; d=c; c=b; b=a; a=t; } #else #define CORE2(i) CORE(i,a,b,c,d) CORE((i+1),d,a,b,c) CORE((i+2),c,d,a,b) CORE((i+3),b,c,d,a) #define CORE4(i) CORE2(i) CORE2((i+4)) CORE2((i+8)) CORE2((i+12)) CORE4(0) CORE4(16) CORE4(32) CORE4(48) #endif ABCD[0] += d; ABCD[1] += c; ABCD[2] += b; ABCD[3] += a; } void av_md5_init(AVMD5 *ctx){ ctx->len = 0; ctx->ABCD[0] = 0x10325476; ctx->ABCD[1] = 0x98badcfe; ctx->ABCD[2] = 0xefcdab89; ctx->ABCD[3] = 0x67452301; } void av_md5_update(AVMD5 *ctx, const uint8_t *src, const int len){ int i, j; j= ctx->len & 63; ctx->len += len; for( i = 0; i < len; i++ ){ ctx->block[j++] = src[i]; if( 64 == j ){ body(ctx->ABCD, (uint32_t*) ctx->block); j = 0; } } } void av_md5_final(AVMD5 *ctx, uint8_t *dst){ int i; uint64_t finalcount= le2me_64(ctx->len<<3); av_md5_update(ctx, "\200", 1); while((ctx->len & 63)!=56) av_md5_update(ctx, "", 1); av_md5_update(ctx, (uint8_t*)&finalcount, 8); for(i=0; i<4; i++) ((uint32_t*)dst)[i]= le2me_32(ctx->ABCD[3-i]); } void av_md5_sum(uint8_t *dst, const uint8_t *src, const int len){ AVMD5 ctx[1]; av_md5_init(ctx); av_md5_update(ctx, src, len); av_md5_final(ctx, dst); } #ifdef TEST #include <stdio.h> #include <inttypes.h> #undef printf int main(void){ uint64_t md5val; int i; uint8_t in[1000]; for(i=0; i<1000; i++) in[i]= i*i; av_md5_sum( (uint8_t*)&md5val, in, 1000); printf("%"PRId64"\n", md5val); av_md5_sum( (uint8_t*)&md5val, in, 63); printf("%"PRId64"\n", md5val); av_md5_sum( (uint8_t*)&md5val, in, 64); printf("%"PRId64"\n", md5val); av_md5_sum( (uint8_t*)&md5val, in, 65); printf("%"PRId64"\n", md5val); for(i=0; i<1000; i++) in[i]= i % 127; av_md5_sum( (uint8_t*)&md5val, in, 999); printf("%"PRId64"\n", md5val); return 0; } #endif
123linslouis-android-video-cutter
jni/libavutil/md5.c
C
asf20
5,365
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * byte swapping routines */ #ifndef AVUTIL_BSWAP_H #define AVUTIL_BSWAP_H #include <stdint.h> #include "config.h" #include "attributes.h" #if ARCH_ARM # include "arm/bswap.h" #elif ARCH_AVR32 # include "avr32/bswap.h" #elif ARCH_BFIN # include "bfin/bswap.h" #elif ARCH_SH4 # include "sh4/bswap.h" #elif ARCH_X86 # include "x86/bswap.h" #endif #define AV_BSWAP16C(x) (((x) << 8 & 0xff00) | ((x) >> 8 & 0x00ff)) #define AV_BSWAP32C(x) (AV_BSWAP16C(x) << 16 | AV_BSWAP16C((x) >> 16)) #define AV_BSWAP64C(x) (AV_BSWAP32C(x) << 32 | AV_BSWAP32C((x) >> 32)) #define AV_BSWAPC(s, x) AV_BSWAP##s##C(x) #ifndef bswap_16 static av_always_inline av_const uint16_t bswap_16(uint16_t x) { x= (x>>8) | (x<<8); return x; } #endif #ifndef bswap_32 static av_always_inline av_const uint32_t bswap_32(uint32_t x) { x= ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF); x= (x>>16) | (x<<16); return x; } #endif #ifndef bswap_64 static inline uint64_t av_const bswap_64(uint64_t x) { #if 0 x= ((x<< 8)&0xFF00FF00FF00FF00ULL) | ((x>> 8)&0x00FF00FF00FF00FFULL); x= ((x<<16)&0xFFFF0000FFFF0000ULL) | ((x>>16)&0x0000FFFF0000FFFFULL); return (x>>32) | (x<<32); #else union { uint64_t ll; uint32_t l[2]; } w, r; w.ll = x; r.l[0] = bswap_32 (w.l[1]); r.l[1] = bswap_32 (w.l[0]); return r.ll; #endif } #endif // be2me ... big-endian to machine-endian // le2me ... little-endian to machine-endian #if HAVE_BIGENDIAN #define be2me_16(x) (x) #define be2me_32(x) (x) #define be2me_64(x) (x) #define le2me_16(x) bswap_16(x) #define le2me_32(x) bswap_32(x) #define le2me_64(x) bswap_64(x) #define AV_BE2MEC(s, x) (x) #define AV_LE2MEC(s, x) AV_BSWAPC(s, x) #else #define be2me_16(x) bswap_16(x) #define be2me_32(x) bswap_32(x) #define be2me_64(x) bswap_64(x) #define le2me_16(x) (x) #define le2me_32(x) (x) #define le2me_64(x) (x) #define AV_BE2MEC(s, x) AV_BSWAPC(s, x) #define AV_LE2MEC(s, x) (x) #endif #define AV_BE2ME16C(x) AV_BE2MEC(16, x) #define AV_BE2ME32C(x) AV_BE2MEC(32, x) #define AV_BE2ME64C(x) AV_BE2MEC(64, x) #define AV_LE2ME16C(x) AV_LE2MEC(16, x) #define AV_LE2ME32C(x) AV_LE2MEC(32, x) #define AV_LE2ME64C(x) AV_LE2MEC(64, x) #endif /* AVUTIL_BSWAP_H */
123linslouis-android-video-cutter
jni/libavutil/bswap.h
C
asf20
3,073
/* * default memory allocator for libavutil * Copyright (c) 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * default memory allocator for libavutil */ #include "config.h" #include <limits.h> #include <stdlib.h> #include <string.h> #if HAVE_MALLOC_H #include <malloc.h> #endif #include "avutil.h" #include "mem.h" /* here we can use OS-dependent allocation functions */ #undef free #undef malloc #undef realloc #ifdef MALLOC_PREFIX #define malloc AV_JOIN(MALLOC_PREFIX, malloc) #define memalign AV_JOIN(MALLOC_PREFIX, memalign) #define posix_memalign AV_JOIN(MALLOC_PREFIX, posix_memalign) #define realloc AV_JOIN(MALLOC_PREFIX, realloc) #define free AV_JOIN(MALLOC_PREFIX, free) void *malloc(size_t size); void *memalign(size_t align, size_t size); int posix_memalign(void **ptr, size_t align, size_t size); void *realloc(void *ptr, size_t size); void free(void *ptr); #endif /* MALLOC_PREFIX */ /* You can redefine av_malloc and av_free in your project to use your memory allocator. You do not need to suppress this file because the linker will do it automatically. */ void *av_malloc(unsigned int size) { void *ptr = NULL; #if CONFIG_MEMALIGN_HACK long diff; #endif /* let's disallow possible ambiguous cases */ if(size > (INT_MAX-16) ) return NULL; #if CONFIG_MEMALIGN_HACK ptr = malloc(size+16); if(!ptr) return ptr; diff= ((-(long)ptr - 1)&15) + 1; ptr = (char*)ptr + diff; ((char*)ptr)[-1]= diff; #elif HAVE_POSIX_MEMALIGN if (posix_memalign(&ptr,16,size)) ptr = NULL; #elif HAVE_MEMALIGN ptr = memalign(16,size); /* Why 64? Indeed, we should align it: on 4 for 386 on 16 for 486 on 32 for 586, PPro - K6-III on 64 for K7 (maybe for P3 too). Because L1 and L2 caches are aligned on those values. But I don't want to code such logic here! */ /* Why 16? Because some CPUs need alignment, for example SSE2 on P4, & most RISC CPUs it will just trigger an exception and the unaligned load will be done in the exception handler or it will just segfault (SSE2 on P4). Why not larger? Because I did not see a difference in benchmarks ... */ /* benchmarks with P3 memalign(64)+1 3071,3051,3032 memalign(64)+2 3051,3032,3041 memalign(64)+4 2911,2896,2915 memalign(64)+8 2545,2554,2550 memalign(64)+16 2543,2572,2563 memalign(64)+32 2546,2545,2571 memalign(64)+64 2570,2533,2558 BTW, malloc seems to do 8-byte alignment by default here. */ #else ptr = malloc(size); #endif return ptr; } void *av_realloc(void *ptr, unsigned int size) { #if CONFIG_MEMALIGN_HACK int diff; #endif /* let's disallow possible ambiguous cases */ if(size > (INT_MAX-16) ) return NULL; #if CONFIG_MEMALIGN_HACK //FIXME this isn't aligned correctly, though it probably isn't needed if(!ptr) return av_malloc(size); diff= ((char*)ptr)[-1]; return (char*)realloc((char*)ptr - diff, size + diff) + diff; #else return realloc(ptr, size); #endif } void av_free(void *ptr) { /* XXX: this test should not be needed on most libcs */ if (ptr) #if CONFIG_MEMALIGN_HACK free((char*)ptr - ((char*)ptr)[-1]); #else free(ptr); #endif } void av_freep(void *arg) { void **ptr= (void**)arg; av_free(*ptr); *ptr = NULL; } void *av_mallocz(unsigned int size) { void *ptr = av_malloc(size); if (ptr) memset(ptr, 0, size); return ptr; } char *av_strdup(const char *s) { char *ptr= NULL; if(s){ int len = strlen(s) + 1; ptr = av_malloc(len); if (ptr) memcpy(ptr, s, len); } return ptr; }
123linslouis-android-video-cutter
jni/libavutil/mem.c
C
asf20
4,618
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * A tree container. * Insertion, removal, finding equal, largest which is smaller than and * smallest which is larger than, all have O(log n) worst case complexity. * @author Michael Niedermayer <michaelni@gmx.at> */ #ifndef AVUTIL_TREE_H #define AVUTIL_TREE_H struct AVTreeNode; extern const int av_tree_node_size; /** * Finds an element. * @param root a pointer to the root node of the tree * @param next If next is not NULL, then next[0] will contain the previous * element and next[1] the next element. If either does not exist, * then the corresponding entry in next is unchanged. * @return An element with cmp(key, elem)==0 or NULL if no such element exists in * the tree. */ void *av_tree_find(const struct AVTreeNode *root, void *key, int (*cmp)(void *key, const void *b), void *next[2]); /** * Inserts or removes an element. * If *next is NULL, then the supplied element will be removed if it exists. * If *next is not NULL, then the supplied element will be inserted, unless * it already exists in the tree. * @param rootp A pointer to a pointer to the root node of the tree; note that * the root node can change during insertions, this is required * to keep the tree balanced. * @param next Used to allocate and free AVTreeNodes. For insertion the user * must set it to an allocated and zeroed object of at least * av_tree_node_size bytes size. av_tree_insert() will set it to * NULL if it has been consumed. * For deleting elements *next is set to NULL by the user and * av_tree_node_size() will set it to the AVTreeNode which was * used for the removed element. * This allows the use of flat arrays, which have * lower overhead compared to many malloced elements. * You might want to define a function like: * @code * void *tree_insert(struct AVTreeNode **rootp, void *key, int (*cmp)(void *key, const void *b), AVTreeNode **next){ * if(!*next) *next= av_mallocz(av_tree_node_size); * return av_tree_insert(rootp, key, cmp, next); * } * void *tree_remove(struct AVTreeNode **rootp, void *key, int (*cmp)(void *key, const void *b, AVTreeNode **next)){ * if(*next) av_freep(next); * return av_tree_insert(rootp, key, cmp, next); * } * @endcode * @return If no insertion happened, the found element; if an insertion or * removal happened, then either key or NULL will be returned. * Which one it is depends on the tree state and the implementation. You * should make no assumptions that it's one or the other in the code. */ void *av_tree_insert(struct AVTreeNode **rootp, void *key, int (*cmp)(void *key, const void *b), struct AVTreeNode **next); void av_tree_destroy(struct AVTreeNode *t); /** * Applies enu(opaque, &elem) to all the elements in the tree in a given range. * * @param cmp a comparison function that returns < 0 for a element below the * range, > 0 for a element above the range and == 0 for a * element inside the range * * @note The cmp function should use the same ordering used to construct the * tree. */ void av_tree_enumerate(struct AVTreeNode *t, void *opaque, int (*cmp)(void *opaque, void *elem), int (*enu)(void *opaque, void *elem)); #endif /* AVUTIL_TREE_H */
123linslouis-android-video-cutter
jni/libavutil/tree.h
C
asf20
4,357
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avutil.h" #include "avstring.h" int av_strerror(int errnum, char *errbuf, size_t errbuf_size) { int ret = 0; const char *errstr = NULL; switch (errnum) { case AVERROR_EOF: errstr = "End of file"; break; case AVERROR_INVALIDDATA: errstr = "Invalid data found when processing input"; break; case AVERROR_NUMEXPECTED: errstr = "Number syntax expected in filename"; break; case AVERROR_PATCHWELCOME: errstr = "Not yet implemented in FFmpeg, patches welcome"; break; } if (errstr) { av_strlcpy(errbuf, errstr, errbuf_size); } else { #if HAVE_STRERROR_R ret = strerror_r(AVUNERROR(errnum), errbuf, errbuf_size); #else ret = -1; #endif if (ret < 0) snprintf(errbuf, errbuf_size, "Error number %d occurred", errnum); } return ret; }
123linslouis-android-video-cutter
jni/libavutil/error.c
C
asf20
1,626
/* * rational numbers * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * rational numbers * @author Michael Niedermayer <michaelni@gmx.at> */ #ifndef AVUTIL_RATIONAL_H #define AVUTIL_RATIONAL_H #include <stdint.h> #include "attributes.h" /** * rational number numerator/denominator */ typedef struct AVRational{ int num; ///< numerator int den; ///< denominator } AVRational; /** * Compares two rationals. * @param a first rational * @param b second rational * @return 0 if a==b, 1 if a>b and -1 if a<b */ static inline int av_cmp_q(AVRational a, AVRational b){ const int64_t tmp= a.num * (int64_t)b.den - b.num * (int64_t)a.den; if(tmp) return (tmp>>63)|1; else return 0; } /** * Converts rational to double. * @param a rational to convert * @return (double) a */ static inline double av_q2d(AVRational a){ return a.num / (double) a.den; } /** * Reduces a fraction. * This is useful for framerate calculations. * @param dst_num destination numerator * @param dst_den destination denominator * @param num source numerator * @param den source denominator * @param max the maximum allowed for dst_num & dst_den * @return 1 if exact, 0 otherwise */ int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max); /** * Multiplies two rationals. * @param b first rational * @param c second rational * @return b*c */ AVRational av_mul_q(AVRational b, AVRational c) av_const; /** * Divides one rational by another. * @param b first rational * @param c second rational * @return b/c */ AVRational av_div_q(AVRational b, AVRational c) av_const; /** * Adds two rationals. * @param b first rational * @param c second rational * @return b+c */ AVRational av_add_q(AVRational b, AVRational c) av_const; /** * Subtracts one rational from another. * @param b first rational * @param c second rational * @return b-c */ AVRational av_sub_q(AVRational b, AVRational c) av_const; /** * Converts a double precision floating point number to a rational. * @param d double to convert * @param max the maximum allowed numerator and denominator * @return (AVRational) d */ AVRational av_d2q(double d, int max) av_const; /** * @return 1 if q1 is nearer to q than q2, -1 if q2 is nearer * than q1, 0 if they have the same distance. */ int av_nearer_q(AVRational q, AVRational q1, AVRational q2); /** * Finds the nearest value in q_list to q. * @param q_list an array of rationals terminated by {0, 0} * @return the index of the nearest value found in the array */ int av_find_nearest_q_idx(AVRational q, const AVRational* q_list); #endif /* AVUTIL_RATIONAL_H */
123linslouis-android-video-cutter
jni/libavutil/rational.h
C
asf20
3,441
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AVR32_BSWAP_H #define AVUTIL_AVR32_BSWAP_H #include <stdint.h> #include "config.h" #include "libavutil/attributes.h" #if HAVE_INLINE_ASM #define bswap_16 bswap_16 static av_always_inline av_const uint16_t bswap_16(uint16_t x) { __asm__ ("swap.bh %0" : "+r"(x)); return x; } #define bswap_32 bswap_32 static av_always_inline av_const uint32_t bswap_32(uint32_t x) { __asm__ ("swap.b %0" : "+r"(x)); return x; } #endif /* HAVE_INLINE_ASM */ #endif /* AVUTIL_AVR32_BSWAP_H */
123linslouis-android-video-cutter
jni/libavutil/avr32/bswap.h
C
asf20
1,275
/* * Copyright (c) 2009 Mans Rullgard <mans@mansr.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AVR32_INTREADWRITE_H #define AVUTIL_AVR32_INTREADWRITE_H #include <stdint.h> #include "config.h" #include "libavutil/bswap.h" /* * AVR32 does not support unaligned memory accesses, except for the AP * series which suppports unaligned 32-bit loads and stores. 16-bit * and 64-bit accesses must be aligned to 16 and 32 bits, respectively. * This means we cannot use the byte-swapping load/store instructions * here. * * For 16-bit, 24-bit, and (on UC series) 32-bit loads, we instead use * the LDINS.B instruction, which gcc fails to utilise with the * generic code. GCC also fails to use plain LD.W and ST.W even for * AP processors, so we override the generic code. The 64-bit * versions are improved by using our optimised 32-bit functions. */ #define AV_RL16 AV_RL16 static av_always_inline uint16_t AV_RL16(const void *p) { uint16_t v; __asm__ ("ld.ub %0, %1 \n\t" "ldins.b %0:l, %2 \n\t" : "=&r"(v) : "m"(*(const uint8_t*)p), "RKs12"(*((const uint8_t*)p+1))); return v; } #define AV_RB16 AV_RB16 static av_always_inline uint16_t AV_RB16(const void *p) { uint16_t v; __asm__ ("ld.ub %0, %2 \n\t" "ldins.b %0:l, %1 \n\t" : "=&r"(v) : "RKs12"(*(const uint8_t*)p), "m"(*((const uint8_t*)p+1))); return v; } #define AV_RB24 AV_RB24 static av_always_inline uint32_t AV_RB24(const void *p) { uint32_t v; __asm__ ("ld.ub %0, %3 \n\t" "ldins.b %0:l, %2 \n\t" "ldins.b %0:u, %1 \n\t" : "=&r"(v) : "RKs12"(* (const uint8_t*)p), "RKs12"(*((const uint8_t*)p+1)), "m" (*((const uint8_t*)p+2))); return v; } #define AV_RL24 AV_RL24 static av_always_inline uint32_t AV_RL24(const void *p) { uint32_t v; __asm__ ("ld.ub %0, %1 \n\t" "ldins.b %0:l, %2 \n\t" "ldins.b %0:u, %3 \n\t" : "=&r"(v) : "m" (* (const uint8_t*)p), "RKs12"(*((const uint8_t*)p+1)), "RKs12"(*((const uint8_t*)p+2))); return v; } #if ARCH_AVR32_AP #define AV_RB32 AV_RB32 static av_always_inline uint32_t AV_RB32(const void *p) { uint32_t v; __asm__ ("ld.w %0, %1" : "=r"(v) : "m"(*(const uint32_t*)p)); return v; } #define AV_WB32 AV_WB32 static av_always_inline void AV_WB32(void *p, uint32_t v) { __asm__ ("st.w %0, %1" : "=m"(*(uint32_t*)p) : "r"(v)); } /* These two would be defined by generic code, but we need them sooner. */ #define AV_RL32(p) bswap_32(AV_RB32(p)) #define AV_WL32(p, v) AV_WB32(p, bswap_32(v)) #define AV_WB64 AV_WB64 static av_always_inline void AV_WB64(void *p, uint64_t v) { union { uint64_t v; uint32_t hl[2]; } vv = { v }; AV_WB32(p, vv.hl[0]); AV_WB32((uint32_t*)p+1, vv.hl[1]); } #define AV_WL64 AV_WL64 static av_always_inline void AV_WL64(void *p, uint64_t v) { union { uint64_t v; uint32_t hl[2]; } vv = { v }; AV_WL32(p, vv.hl[1]); AV_WL32((uint32_t*)p+1, vv.hl[0]); } #else /* ARCH_AVR32_AP */ #define AV_RB32 AV_RB32 static av_always_inline uint32_t AV_RB32(const void *p) { uint32_t v; __asm__ ("ld.ub %0, %4 \n\t" "ldins.b %0:l, %3 \n\t" "ldins.b %0:u, %2 \n\t" "ldins.b %0:t, %1 \n\t" : "=&r"(v) : "RKs12"(* (const uint8_t*)p), "RKs12"(*((const uint8_t*)p+1)), "RKs12"(*((const uint8_t*)p+2)), "m" (*((const uint8_t*)p+3))); return v; } #define AV_RL32 AV_RL32 static av_always_inline uint32_t AV_RL32(const void *p) { uint32_t v; __asm__ ("ld.ub %0, %1 \n\t" "ldins.b %0:l, %2 \n\t" "ldins.b %0:u, %3 \n\t" "ldins.b %0:t, %4 \n\t" : "=&r"(v) : "m" (* (const uint8_t*)p), "RKs12"(*((const uint8_t*)p+1)), "RKs12"(*((const uint8_t*)p+2)), "RKs12"(*((const uint8_t*)p+3))); return v; } #endif /* ARCH_AVR32_AP */ #define AV_RB64 AV_RB64 static av_always_inline uint64_t AV_RB64(const void *p) { union { uint64_t v; uint32_t hl[2]; } v; v.hl[0] = AV_RB32(p); v.hl[1] = AV_RB32((const uint32_t*)p+1); return v.v; } #define AV_RL64 AV_RL64 static av_always_inline uint64_t AV_RL64(const void *p) { union { uint64_t v; uint32_t hl[2]; } v; v.hl[1] = AV_RL32(p); v.hl[0] = AV_RL32((const uint32_t*)p+1); return v.v; } #endif /* AVUTIL_AVR32_INTREADWRITE_H */
123linslouis-android-video-cutter
jni/libavutil/avr32/intreadwrite.h
C
asf20
5,400
/* * copyright (c) 2006 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_ADLER32_H #define AVUTIL_ADLER32_H #include <stdint.h> #include "attributes.h" unsigned long av_adler32_update(unsigned long adler, const uint8_t *buf, unsigned int len) av_pure; #endif /* AVUTIL_ADLER32_H */
123linslouis-android-video-cutter
jni/libavutil/adler32.h
C
asf20
1,062
/* * DES encryption/decryption * Copyright (c) 2007 Reimar Doeffinger * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_DES_H #define AVUTIL_DES_H #include <stdint.h> struct AVDES { uint64_t round_keys[3][16]; int triple_des; }; /** * \brief Initializes an AVDES context. * * \param key_bits must be 64 or 192 * \param decrypt 0 for encryption, 1 for decryption */ int av_des_init(struct AVDES *d, const uint8_t *key, int key_bits, int decrypt); /** * \brief Encrypts / decrypts using the DES algorithm. * * \param count number of 8 byte blocks * \param dst destination array, can be equal to src, must be 8-byte aligned * \param src source array, can be equal to dst, must be 8-byte aligned, may be NULL * \param iv initialization vector for CBC mode, if NULL then ECB will be used, * must be 8-byte aligned * \param decrypt 0 for encryption, 1 for decryption */ void av_des_crypt(struct AVDES *d, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); #endif /* AVUTIL_DES_H */
123linslouis-android-video-cutter
jni/libavutil/des.h
C
asf20
1,765
/* * arbitrary precision integers * Copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * arbitrary precision integers * @author Michael Niedermayer <michaelni@gmx.at> */ #include "common.h" #include "integer.h" AVInteger av_add_i(AVInteger a, AVInteger b){ int i, carry=0; for(i=0; i<AV_INTEGER_SIZE; i++){ carry= (carry>>16) + a.v[i] + b.v[i]; a.v[i]= carry; } return a; } AVInteger av_sub_i(AVInteger a, AVInteger b){ int i, carry=0; for(i=0; i<AV_INTEGER_SIZE; i++){ carry= (carry>>16) + a.v[i] - b.v[i]; a.v[i]= carry; } return a; } int av_log2_i(AVInteger a){ int i; for(i=AV_INTEGER_SIZE-1; i>=0; i--){ if(a.v[i]) return av_log2_16bit(a.v[i]) + 16*i; } return -1; } AVInteger av_mul_i(AVInteger a, AVInteger b){ AVInteger out; int i, j; int na= (av_log2_i(a)+16) >> 4; int nb= (av_log2_i(b)+16) >> 4; memset(&out, 0, sizeof(out)); for(i=0; i<na; i++){ unsigned int carry=0; if(a.v[i]) for(j=i; j<AV_INTEGER_SIZE && j-i<=nb; j++){ carry= (carry>>16) + out.v[j] + a.v[i]*b.v[j-i]; out.v[j]= carry; } } return out; } int av_cmp_i(AVInteger a, AVInteger b){ int i; int v= (int16_t)a.v[AV_INTEGER_SIZE-1] - (int16_t)b.v[AV_INTEGER_SIZE-1]; if(v) return (v>>16)|1; for(i=AV_INTEGER_SIZE-2; i>=0; i--){ int v= a.v[i] - b.v[i]; if(v) return (v>>16)|1; } return 0; } AVInteger av_shr_i(AVInteger a, int s){ AVInteger out; int i; for(i=0; i<AV_INTEGER_SIZE; i++){ unsigned int index= i + (s>>4); unsigned int v=0; if(index+1<AV_INTEGER_SIZE) v = a.v[index+1]<<16; if(index <AV_INTEGER_SIZE) v+= a.v[index ]; out.v[i]= v >> (s&15); } return out; } AVInteger av_mod_i(AVInteger *quot, AVInteger a, AVInteger b){ int i= av_log2_i(a) - av_log2_i(b); AVInteger quot_temp; if(!quot) quot = &quot_temp; assert((int16_t)a[AV_INTEGER_SIZE-1] >= 0 && (int16_t)b[AV_INTEGER_SIZE-1] >= 0); assert(av_log2(b)>=0); if(i > 0) b= av_shr_i(b, -i); memset(quot, 0, sizeof(AVInteger)); while(i-- >= 0){ *quot= av_shr_i(*quot, -1); if(av_cmp_i(a, b) >= 0){ a= av_sub_i(a, b); quot->v[0] += 1; } b= av_shr_i(b, 1); } return a; } AVInteger av_div_i(AVInteger a, AVInteger b){ AVInteger quot; av_mod_i(&quot, a, b); return quot; } AVInteger av_int2i(int64_t a){ AVInteger out; int i; for(i=0; i<AV_INTEGER_SIZE; i++){ out.v[i]= a; a>>=16; } return out; } int64_t av_i2int(AVInteger a){ int i; int64_t out=(int8_t)a.v[AV_INTEGER_SIZE-1]; for(i= AV_INTEGER_SIZE-2; i>=0; i--){ out = (out<<16) + a.v[i]; } return out; } #ifdef TEST #undef NDEBUG #include <assert.h> const uint8_t ff_log2_tab[256]={ 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 }; int main(void){ int64_t a,b; for(a=7; a<256*256*256; a+=13215){ for(b=3; b<256*256*256; b+=27118){ AVInteger ai= av_int2i(a); AVInteger bi= av_int2i(b); assert(av_i2int(ai) == a); assert(av_i2int(bi) == b); assert(av_i2int(av_add_i(ai,bi)) == a+b); assert(av_i2int(av_sub_i(ai,bi)) == a-b); assert(av_i2int(av_mul_i(ai,bi)) == a*b); assert(av_i2int(av_shr_i(ai, 9)) == a>>9); assert(av_i2int(av_shr_i(ai,-9)) == a<<9); assert(av_i2int(av_shr_i(ai, 17)) == a>>17); assert(av_i2int(av_shr_i(ai,-17)) == a<<17); assert(av_log2_i(ai) == av_log2(a)); assert(av_i2int(av_div_i(ai,bi)) == a/b); } } return 0; } #endif
123linslouis-android-video-cutter
jni/libavutil/integer.c
C
asf20
5,160
/* * linear least squares model * * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_LLS_H #define AVUTIL_LLS_H #define MAX_VARS 32 //FIXME avoid direct access to LLSModel from outside /** * Linear least squares model. */ typedef struct LLSModel{ double covariance[MAX_VARS+1][MAX_VARS+1]; double coeff[MAX_VARS][MAX_VARS]; double variance[MAX_VARS]; int indep_count; }LLSModel; void av_init_lls(LLSModel *m, int indep_count); void av_update_lls(LLSModel *m, double *param, double decay); void av_solve_lls(LLSModel *m, double threshold, int min_order); double av_evaluate_lls(LLSModel *m, double *param, int order); #endif /* AVUTIL_LLS_H */
123linslouis-android-video-cutter
jni/libavutil/lls.h
C
asf20
1,457
LIBAVUTIL_$MAJOR { global: av_*; ff_*; avutil_*; local: *; };
123linslouis-android-video-cutter
jni/libavutil/libavutil.v
Verilog
asf20
78
/* * log functions * Copyright (c) 2003 Michel Bardiaux * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * logging functions */ #include <unistd.h> #include <stdlib.h> #include "avutil.h" #include "log.h" #if LIBAVUTIL_VERSION_MAJOR > 50 static #endif int av_log_level = AV_LOG_INFO; static int use_ansi_color=-1; #undef fprintf static void colored_fputs(int color, const char *str){ if(use_ansi_color<0){ #if HAVE_ISATTY && !defined(_WIN32) use_ansi_color= getenv("TERM") && !getenv("NO_COLOR") && isatty(2); #else use_ansi_color= 0; #endif } if(use_ansi_color){ fprintf(stderr, "\033[%d;3%dm", color>>4, color&15); } fputs(str, stderr); if(use_ansi_color){ fprintf(stderr, "\033[0m"); } } void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl) { static int print_prefix=1; static int count; static char line[1024], prev[1024]; static const uint8_t color[]={0x41,0x41,0x11,0x03,9,9,9}; AVClass* avc= ptr ? *(AVClass**)ptr : NULL; if(level>av_log_level) return; #undef fprintf if(print_prefix && avc) { snprintf(line, sizeof(line), "[%s @ %p]", avc->item_name(ptr), ptr); }else line[0]=0; vsnprintf(line + strlen(line), sizeof(line) - strlen(line), fmt, vl); print_prefix= line[strlen(line)-1] == '\n'; if(print_prefix && !strcmp(line, prev)){ count++; return; } if(count>0){ fprintf(stderr, " Last message repeated %d times\n", count); count=0; } colored_fputs(color[av_clip(level>>3, 0, 6)], line); strcpy(prev, line); } static void (*av_log_callback)(void*, int, const char*, va_list) = av_log_default_callback; void av_log(void* avcl, int level, const char *fmt, ...) { va_list vl; va_start(vl, fmt); av_vlog(avcl, level, fmt, vl); va_end(vl); } void av_vlog(void* avcl, int level, const char *fmt, va_list vl) { av_log_callback(avcl, level, fmt, vl); } int av_log_get_level(void) { return av_log_level; } void av_log_set_level(int level) { av_log_level = level; } void av_log_set_callback(void (*callback)(void*, int, const char*, va_list)) { av_log_callback = callback; }
123linslouis-android-video-cutter
jni/libavutil/log.c
C
asf20
2,964
/* * Copyright (c) 2005 Luca Barbato <lu_zero@gentoo.org> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PPC_TIMER_H #define AVUTIL_PPC_TIMER_H #include <stdint.h> #define AV_READ_TIME read_time static inline uint64_t read_time(void) { uint32_t tbu, tbl, temp; /* from section 2.2.1 of the 32-bit PowerPC PEM */ __asm__ volatile( "1:\n" "mftbu %2\n" "mftb %0\n" "mftbu %1\n" "cmpw %2,%1\n" "bne 1b\n" : "=r"(tbl), "=r"(tbu), "=r"(temp) : : "cc"); return (((uint64_t)tbu)<<32) | (uint64_t)tbl; } #endif /* AVUTIL_PPC_TIMER_H */
123linslouis-android-video-cutter
jni/libavutil/ppc/timer.h
C
asf20
1,363
/* * Copyright (c) 2008 Mans Rullgard <mans@mansr.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PPC_INTREADWRITE_H #define AVUTIL_PPC_INTREADWRITE_H #include <stdint.h> #include "config.h" #if HAVE_XFORM_ASM #define AV_RL16 AV_RL16 static av_always_inline uint16_t AV_RL16(const void *p) { uint16_t v; __asm__ ("lhbrx %0, %y1" : "=r"(v) : "Z"(*(const uint16_t*)p)); return v; } #define AV_WL16 AV_WL16 static av_always_inline void AV_WL16(void *p, uint16_t v) { __asm__ ("sthbrx %1, %y0" : "=Z"(*(uint16_t*)p) : "r"(v)); } #define AV_RL32 AV_RL32 static av_always_inline uint32_t AV_RL32(const void *p) { uint32_t v; __asm__ ("lwbrx %0, %y1" : "=r"(v) : "Z"(*(const uint32_t*)p)); return v; } #define AV_WL32 AV_WL32 static av_always_inline void AV_WL32(void *p, uint32_t v) { __asm__ ("stwbrx %1, %y0" : "=Z"(*(uint32_t*)p) : "r"(v)); } #if HAVE_LDBRX #define AV_RL64 AV_RL64 static av_always_inline uint64_t AV_RL64(const void *p) { uint64_t v; __asm__ ("ldbrx %0, %y1" : "=r"(v) : "Z"(*(const uint64_t*)p)); return v; } #define AV_WL64 AV_WL64 static av_always_inline void AV_WL64(void *p, uint64_t v) { __asm__ ("stdbrx %1, %y0" : "=Z"(*(uint64_t*)p) : "r"(v)); } #else #define AV_RL64 AV_RL64 static av_always_inline uint64_t AV_RL64(const void *p) { union { uint64_t v; uint32_t hl[2]; } v; __asm__ ("lwbrx %0, %y2 \n\t" "lwbrx %1, %y3 \n\t" : "=&r"(v.hl[1]), "=r"(v.hl[0]) : "Z"(*(const uint32_t*)p), "Z"(*((const uint32_t*)p+1))); return v.v; } #define AV_WL64 AV_WL64 static av_always_inline void AV_WL64(void *p, uint64_t v) { union { uint64_t v; uint32_t hl[2]; } vv = { v }; __asm__ ("stwbrx %2, %y0 \n\t" "stwbrx %3, %y1 \n\t" : "=Z"(*(uint32_t*)p), "=Z"(*((uint32_t*)p+1)) : "r"(vv.hl[1]), "r"(vv.hl[0])); } #endif /* HAVE_LDBRX */ #endif /* HAVE_XFORM_ASM */ /* * GCC fails miserably on the packed struct version which is used by * default, so we override it here. */ #define AV_RB64(p) (*(const uint64_t *)(p)) #define AV_WB64(p, v) (*(uint64_t *)(p) = (v)) #endif /* AVUTIL_PPC_INTREADWRITE_H */
123linslouis-android-video-cutter
jni/libavutil/ppc/intreadwrite.h
C
asf20
2,937
/* * Copyright (c) 2010 Mans Rullgard <mans@mansr.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_INTMATH_H #define AVUTIL_INTMATH_H #include <stdint.h> #include "config.h" #include "attributes.h" extern const uint32_t ff_inverse[257]; #if ARCH_ARM # include "arm/intmath.h" #elif ARCH_X86 # include "x86/intmath.h" #endif #if HAVE_FAST_CLZ && AV_GCC_VERSION_AT_LEAST(3,4) #ifndef av_log2 #define av_log2(x) (31 - __builtin_clz((x)|1)) #ifndef av_log2_16bit #define av_log2_16bit av_log2 #endif #endif /* av_log2 */ #endif /* AV_GCC_VERSION_AT_LEAST(3,4) */ #ifndef FASTDIV #if CONFIG_FASTDIV # define FASTDIV(a,b) ((uint32_t)((((uint64_t)a) * ff_inverse[b]) >> 32)) #else # define FASTDIV(a,b) ((a) / (b)) #endif #endif /* FASTDIV */ /* * Get definition of av_log2_c from common.h. In the event we got * here through common.h including this file, including it again will * be a no-op due to multi-inclusion guards, so we must duplicate the * fallback defines here. */ #include "common.h" #ifndef av_log2 # define av_log2 av_log2_c #endif #ifndef av_log2_16bit # define av_log2_16bit av_log2_16bit_c #endif extern const uint8_t ff_sqrt_tab[256]; static inline av_const unsigned int ff_sqrt(unsigned int a) { unsigned int b; if (a < 255) return (ff_sqrt_tab[a + 1] - 1) >> 4; else if (a < (1 << 12)) b = ff_sqrt_tab[a >> 4] >> 2; #if !CONFIG_SMALL else if (a < (1 << 14)) b = ff_sqrt_tab[a >> 6] >> 1; else if (a < (1 << 16)) b = ff_sqrt_tab[a >> 8] ; #endif else { int s = av_log2_16bit(a >> 16) >> 1; unsigned int c = a >> (s + 2); b = ff_sqrt_tab[c >> (s + 8)]; b = FASTDIV(c,b) + (b << s); } return b - (a < b * b); } #endif /* AVUTIL_INTMATH_H */
123linslouis-android-video-cutter
jni/libavutil/intmath.h
C
asf20
2,506
/* * Compute the Adler-32 checksum of a data stream. * This is a modified version based on adler32.c from the zlib library. * * Copyright (C) 1995 Mark Adler * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "config.h" #include "adler32.h" #define BASE 65521L /* largest prime smaller than 65536 */ #define DO1(buf) {s1 += *buf++; s2 += s1;} #define DO4(buf) DO1(buf); DO1(buf); DO1(buf); DO1(buf); #define DO16(buf) DO4(buf); DO4(buf); DO4(buf); DO4(buf); unsigned long av_adler32_update(unsigned long adler, const uint8_t *buf, unsigned int len) { unsigned long s1 = adler & 0xffff; unsigned long s2 = adler >> 16; while (len>0) { #if CONFIG_SMALL while(len>4 && s2 < (1U<<31)){ DO4(buf); len-=4; #else while(len>16 && s2 < (1U<<31)){ DO16(buf); len-=16; #endif } DO1(buf); len--; s1 %= BASE; s2 %= BASE; } return (s2 << 16) | s1; } #ifdef TEST #include "log.h" #include "timer.h" #define LEN 7001 volatile int checksum; int main(void){ int i; char data[LEN]; av_log_set_level(AV_LOG_DEBUG); for(i=0; i<LEN; i++) data[i]= ((i*i)>>3) + 123*i; for(i=0; i<1000; i++){ START_TIMER checksum= av_adler32_update(1, data, LEN); STOP_TIMER("adler") } av_log(NULL, AV_LOG_DEBUG, "%X == 50E6E508\n", checksum); return 0; } #endif
123linslouis-android-video-cutter
jni/libavutil/adler32.c
C
asf20
2,217
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * byte swapping routines */ #ifndef AVUTIL_X86_BSWAP_H #define AVUTIL_X86_BSWAP_H #include <stdint.h> #include "config.h" #include "libavutil/attributes.h" #define bswap_16 bswap_16 static av_always_inline av_const uint16_t bswap_16(uint16_t x) { __asm__("rorw $8, %0" : "+r"(x)); return x; } #define bswap_32 bswap_32 static av_always_inline av_const uint32_t bswap_32(uint32_t x) { #if HAVE_BSWAP __asm__("bswap %0" : "+r" (x)); #else __asm__("rorw $8, %w0 \n\t" "rorl $16, %0 \n\t" "rorw $8, %w0" : "+r"(x)); #endif return x; } #if ARCH_X86_64 #define bswap_64 bswap_64 static inline uint64_t av_const bswap_64(uint64_t x) { __asm__("bswap %0": "=r" (x) : "0" (x)); return x; } #endif #endif /* AVUTIL_X86_BSWAP_H */
123linslouis-android-video-cutter
jni/libavutil/x86/bswap.h
C
asf20
1,584
/* * Copyright (c) 2010 Mans Rullgard <mans@mansr.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_X86_INTMATH_H #define AVUTIL_X86_INTMATH_H #define FASTDIV(a,b) \ ({\ int ret, dmy;\ __asm__ volatile(\ "mull %3"\ :"=d"(ret), "=a"(dmy)\ :"1"(a), "g"(ff_inverse[b])\ );\ ret;\ }) #endif /* AVUTIL_X86_INTMATH_H */
123linslouis-android-video-cutter
jni/libavutil/x86/intmath.h
C
asf20
1,131
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_X86_TIMER_H #define AVUTIL_X86_TIMER_H #include <stdint.h> #define AV_READ_TIME read_time static inline uint64_t read_time(void) { uint32_t a, d; __asm__ volatile("rdtsc" : "=a" (a), "=d" (d)); return ((uint64_t)d << 32) + a; } #endif /* AVUTIL_X86_TIMER_H */
123linslouis-android-video-cutter
jni/libavutil/x86/timer.h
C
asf20
1,119
/* * Copyright (c) 2010 Alexander Strange <astrange@ithinksw.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_X86_INTREADWRITE_H #define AVUTIL_X86_INTREADWRITE_H #include <stdint.h> #include "config.h" #include "libavutil/attributes.h" #if HAVE_MMX #if !HAVE_FAST_64BIT && defined(__MMX__) #define AV_COPY64 AV_COPY64 static av_always_inline void AV_COPY64(void *d, const void *s) { __asm__("movq %1, %%mm0 \n\t" "movq %%mm0, %0 \n\t" : "=m"(*(uint64_t*)d) : "m" (*(const uint64_t*)s) : "mm0"); } #define AV_SWAP64 AV_SWAP64 static av_always_inline void AV_SWAP64(void *a, void *b) { __asm__("movq %1, %%mm0 \n\t" "movq %0, %%mm1 \n\t" "movq %%mm0, %0 \n\t" "movq %%mm1, %1 \n\t" : "+m"(*(uint64_t*)a), "+m"(*(uint64_t*)b) ::"mm0", "mm1"); } #define AV_ZERO64 AV_ZERO64 static av_always_inline void AV_ZERO64(void *d) { __asm__("pxor %%mm0, %%mm0 \n\t" "movq %%mm0, %0 \n\t" : "=m"(*(uint64_t*)d) :: "mm0"); } #endif /* !HAVE_FAST_64BIT && defined(__MMX__) */ #ifdef __SSE__ #define AV_COPY128 AV_COPY128 static av_always_inline void AV_COPY128(void *d, const void *s) { struct v {uint64_t v[2];}; __asm__("movaps %1, %%xmm0 \n\t" "movaps %%xmm0, %0 \n\t" : "=m"(*(struct v*)d) : "m" (*(const struct v*)s) : "xmm0"); } #endif /* __SSE__ */ #ifdef __SSE2__ #define AV_ZERO128 AV_ZERO128 static av_always_inline void AV_ZERO128(void *d) { struct v {uint64_t v[2];}; __asm__("pxor %%xmm0, %%xmm0 \n\t" "movdqa %%xmm0, %0 \n\t" : "=m"(*(struct v*)d) :: "xmm0"); } #endif /* __SSE2__ */ #endif /* HAVE_MMX */ #endif /* AVUTIL_X86_INTREADWRITE_H */
123linslouis-android-video-cutter
jni/libavutil/x86/intreadwrite.h
C
asf20
2,586
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * common internal API header */ #ifndef AVUTIL_INTERNAL_H #define AVUTIL_INTERNAL_H #if !defined(DEBUG) && !defined(NDEBUG) # define NDEBUG #endif #include <limits.h> #include <stdint.h> #include <stddef.h> #include <assert.h> #include "config.h" #include "attributes.h" #include "timer.h" #ifndef attribute_align_arg #if (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(4,2) # define attribute_align_arg __attribute__((force_align_arg_pointer)) #else # define attribute_align_arg #endif #endif #ifndef attribute_used #if AV_GCC_VERSION_AT_LEAST(3,1) # define attribute_used __attribute__((used)) #else # define attribute_used #endif #endif #ifndef av_alias #if HAVE_ATTRIBUTE_MAY_ALIAS && (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(3,3) # define av_alias __attribute__((may_alias)) #else # define av_alias #endif #endif #ifndef INT16_MIN #define INT16_MIN (-0x7fff - 1) #endif #ifndef INT16_MAX #define INT16_MAX 0x7fff #endif #ifndef INT32_MIN #define INT32_MIN (-0x7fffffff - 1) #endif #ifndef INT32_MAX #define INT32_MAX 0x7fffffff #endif #ifndef UINT32_MAX #define UINT32_MAX 0xffffffff #endif #ifndef INT64_MIN #define INT64_MIN (-0x7fffffffffffffffLL - 1) #endif #ifndef INT64_MAX #define INT64_MAX INT64_C(9223372036854775807) #endif #ifndef UINT64_MAX #define UINT64_MAX UINT64_C(0xFFFFFFFFFFFFFFFF) #endif #ifndef INT_BIT # define INT_BIT (CHAR_BIT * sizeof(int)) #endif #ifndef offsetof # define offsetof(T, F) ((unsigned int)((char *)&((T *)0)->F)) #endif /* Use to export labels from asm. */ #define LABEL_MANGLE(a) EXTERN_PREFIX #a // Use rip-relative addressing if compiling PIC code on x86-64. #if ARCH_X86_64 && defined(PIC) # define LOCAL_MANGLE(a) #a "(%%rip)" #else # define LOCAL_MANGLE(a) #a #endif #define MANGLE(a) EXTERN_PREFIX LOCAL_MANGLE(a) /* debug stuff */ /* dprintf macros */ #ifdef DEBUG # define dprintf(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__) #else # define dprintf(pctx, ...) #endif #define av_abort() do { av_log(NULL, AV_LOG_ERROR, "Abort at %s:%d\n", __FILE__, __LINE__); abort(); } while (0) /* math */ #if ARCH_X86 #define MASK_ABS(mask, level)\ __asm__ volatile(\ "cltd \n\t"\ "xorl %1, %0 \n\t"\ "subl %1, %0 \n\t"\ : "+a" (level), "=&d" (mask)\ ); #else #define MASK_ABS(mask, level)\ mask = level >> 31;\ level = (level ^ mask) - mask; #endif /* avoid usage of dangerous/inappropriate system functions */ #undef malloc #define malloc please_use_av_malloc #undef free #define free please_use_av_free #undef realloc #define realloc please_use_av_realloc #undef time #define time time_is_forbidden_due_to_security_issues #undef rand #define rand rand_is_forbidden_due_to_state_trashing_use_av_lfg_get #undef srand #define srand srand_is_forbidden_due_to_state_trashing_use_av_lfg_init #undef random #define random random_is_forbidden_due_to_state_trashing_use_av_lfg_get #undef sprintf #define sprintf sprintf_is_forbidden_due_to_security_issues_use_snprintf #undef strcat #define strcat strcat_is_forbidden_due_to_security_issues_use_av_strlcat #undef exit #define exit exit_is_forbidden #ifndef LIBAVFORMAT_BUILD #undef printf #define printf please_use_av_log_instead_of_printf #undef fprintf #define fprintf please_use_av_log_instead_of_fprintf #undef puts #define puts please_use_av_log_instead_of_puts #undef perror #define perror please_use_av_log_instead_of_perror #endif #define FF_ALLOC_OR_GOTO(ctx, p, size, label)\ {\ p = av_malloc(size);\ if (p == NULL && (size) != 0) {\ av_log(ctx, AV_LOG_ERROR, "Cannot allocate memory.\n");\ goto label;\ }\ } #define FF_ALLOCZ_OR_GOTO(ctx, p, size, label)\ {\ p = av_mallocz(size);\ if (p == NULL && (size) != 0) {\ av_log(ctx, AV_LOG_ERROR, "Cannot allocate memory.\n");\ goto label;\ }\ } #include "libm.h" /** * Returns NULL if CONFIG_SMALL is true, otherwise the argument * without modification. Used to disable the definition of strings * (for example AVCodec long_names). */ #if CONFIG_SMALL # define NULL_IF_CONFIG_SMALL(x) NULL #else # define NULL_IF_CONFIG_SMALL(x) x #endif #if HAVE_SYMVER_ASM_LABEL # define FF_SYMVER(type, name, args, ver) \ type ff_##name args __asm__ (EXTERN_PREFIX #name "@" ver); \ type ff_##name args #elif HAVE_SYMVER_GNU_ASM # define FF_SYMVER(type, name, args, ver) \ __asm__ (".symver ff_" #name "," EXTERN_PREFIX #name "@" ver); \ type ff_##name args; \ type ff_##name args #endif #endif /* AVUTIL_INTERNAL_H */
123linslouis-android-video-cutter
jni/libavutil/internal.h
C
asf20
5,691
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * memory handling functions */ #ifndef AVUTIL_MEM_H #define AVUTIL_MEM_H #include "attributes.h" #if defined(__ICC) || defined(__SUNPRO_C) #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v #define DECLARE_ASM_CONST(n,t,v) const t __attribute__ ((aligned (n))) v #elif defined(__TI_COMPILER_VERSION__) #define DECLARE_ALIGNED(n,t,v) \ AV_PRAGMA(DATA_ALIGN(v,n)) \ t __attribute__((aligned(n))) v #define DECLARE_ASM_CONST(n,t,v) \ AV_PRAGMA(DATA_ALIGN(v,n)) \ static const t __attribute__((aligned(n))) v #elif defined(__GNUC__) #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v #define DECLARE_ASM_CONST(n,t,v) static const t attribute_used __attribute__ ((aligned (n))) v #elif defined(_MSC_VER) #define DECLARE_ALIGNED(n,t,v) __declspec(align(n)) t v #define DECLARE_ASM_CONST(n,t,v) __declspec(align(n)) static const t v #else #define DECLARE_ALIGNED(n,t,v) t v #define DECLARE_ASM_CONST(n,t,v) static const t v #endif #if AV_GCC_VERSION_AT_LEAST(3,1) #define av_malloc_attrib __attribute__((__malloc__)) #else #define av_malloc_attrib #endif #if (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(4,3) #define av_alloc_size(n) __attribute__((alloc_size(n))) #else #define av_alloc_size(n) #endif /** * Allocates a block of size bytes with alignment suitable for all * memory accesses (including vectors if available on the CPU). * @param size Size in bytes for the memory block to be allocated. * @return Pointer to the allocated block, NULL if the block cannot * be allocated. * @see av_mallocz() */ void *av_malloc(unsigned int size) av_malloc_attrib av_alloc_size(1); /** * Allocates or reallocates a block of memory. * If ptr is NULL and size > 0, allocates a new block. If * size is zero, frees the memory block pointed to by ptr. * @param size Size in bytes for the memory block to be allocated or * reallocated. * @param ptr Pointer to a memory block already allocated with * av_malloc(z)() or av_realloc() or NULL. * @return Pointer to a newly reallocated block or NULL if the block * cannot be reallocated or the function is used to free the memory block. * @see av_fast_realloc() */ void *av_realloc(void *ptr, unsigned int size) av_alloc_size(2); /** * Frees a memory block which has been allocated with av_malloc(z)() or * av_realloc(). * @param ptr Pointer to the memory block which should be freed. * @note ptr = NULL is explicitly allowed. * @note It is recommended that you use av_freep() instead. * @see av_freep() */ void av_free(void *ptr); /** * Allocates a block of size bytes with alignment suitable for all * memory accesses (including vectors if available on the CPU) and * zeroes all the bytes of the block. * @param size Size in bytes for the memory block to be allocated. * @return Pointer to the allocated block, NULL if it cannot be allocated. * @see av_malloc() */ void *av_mallocz(unsigned int size) av_malloc_attrib av_alloc_size(1); /** * Duplicates the string s. * @param s string to be duplicated * @return Pointer to a newly allocated string containing a * copy of s or NULL if the string cannot be allocated. */ char *av_strdup(const char *s) av_malloc_attrib; /** * Frees a memory block which has been allocated with av_malloc(z)() or * av_realloc() and set the pointer pointing to it to NULL. * @param ptr Pointer to the pointer to the memory block which should * be freed. * @see av_free() */ void av_freep(void *ptr); #endif /* AVUTIL_MEM_H */
123linslouis-android-video-cutter
jni/libavutil/mem.h
C
asf20
4,529
/** * @file * high precision timer, useful to profile code * * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_TIMER_H #define AVUTIL_TIMER_H #include <stdlib.h> #include <stdint.h> #include "config.h" #if ARCH_ARM # include "arm/timer.h" #elif ARCH_BFIN # include "bfin/timer.h" #elif ARCH_PPC # include "ppc/timer.h" #elif ARCH_X86 # include "x86/timer.h" #endif #if !defined(AV_READ_TIME) && HAVE_GETHRTIME # define AV_READ_TIME gethrtime #endif #ifdef AV_READ_TIME #define START_TIMER \ uint64_t tend;\ uint64_t tstart= AV_READ_TIME();\ #define STOP_TIMER(id) \ tend= AV_READ_TIME();\ {\ static uint64_t tsum=0;\ static int tcount=0;\ static int tskip_count=0;\ if(tcount<2 || tend - tstart < 8*tsum/tcount || tend - tstart < 2000){\ tsum+= tend - tstart;\ tcount++;\ }else\ tskip_count++;\ if(((tcount+tskip_count)&(tcount+tskip_count-1))==0){\ av_log(NULL, AV_LOG_ERROR, "%"PRIu64" dezicycles in %s, %d runs, %d skips\n",\ tsum*10/tcount, id, tcount, tskip_count);\ }\ } #else #define START_TIMER #define STOP_TIMER(id) {} #endif #endif /* AVUTIL_TIMER_H */
123linslouis-android-video-cutter
jni/libavutil/timer.h
C
asf20
1,950
/* * copyright (c) 2007 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AES_H #define AVUTIL_AES_H #include <stdint.h> extern const int av_aes_size; struct AVAES; /** * Initializes an AVAES context. * @param key_bits 128, 192 or 256 * @param decrypt 0 for encryption, 1 for decryption */ int av_aes_init(struct AVAES *a, const uint8_t *key, int key_bits, int decrypt); /** * Encrypts / decrypts. * @param count number of 16 byte blocks * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param iv initialization vector for CBC mode, if NULL then ECB will be used * @param decrypt 0 for encryption, 1 for decryption */ void av_aes_crypt(struct AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); #endif /* AVUTIL_AES_H */
123linslouis-android-video-cutter
jni/libavutil/aes.h
C
asf20
1,589
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_MD5_H #define AVUTIL_MD5_H #include <stdint.h> extern const int av_md5_size; struct AVMD5; void av_md5_init(struct AVMD5 *ctx); void av_md5_update(struct AVMD5 *ctx, const uint8_t *src, const int len); void av_md5_final(struct AVMD5 *ctx, uint8_t *dst); void av_md5_sum(uint8_t *dst, const uint8_t *src, const int len); #endif /* AVUTIL_MD5_H */
123linslouis-android-video-cutter
jni/libavutil/md5.h
C
asf20
1,195
NAME = avutil HEADERS = adler32.h \ attributes.h \ avstring.h \ avutil.h \ base64.h \ common.h \ crc.h \ error.h \ fifo.h \ intfloat_readwrite.h \ log.h \ lzo.h \ mathematics.h \ md5.h \ mem.h \ pixdesc.h \ pixfmt.h \ rational.h \ sha1.h \ BUILT_HEADERS = avconfig.h OBJS = adler32.o \ aes.o \ avstring.o \ base64.o \ crc.o \ des.o \ error.o \ fifo.o \ intfloat_readwrite.o \ lfg.o \ lls.o \ log.o \ lzo.o \ mathematics.o \ md5.o \ mem.o \ pixdesc.o \ random_seed.o \ rational.o \ rc4.o \ sha.o \ tree.o \ utils.o \ TESTPROGS = adler32 aes base64 crc des lls md5 pca sha softfloat tree TESTPROGS-$(HAVE_LZO1X_999_COMPRESS) += lzo DIRS = arm bfin sh4 x86 ARCH_HEADERS = bswap.h intmath.h intreadwrite.h timer.h $(SUBDIR)lzo-test$(EXESUF): ELIBS = -llzo2
123linslouis-android-video-cutter
jni/libavutil/Makefile
Makefile
asf20
3,397
/* * Copyright (C) 2007 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_SHA_H #define AVUTIL_SHA_H #include <stdint.h> extern const int av_sha_size; struct AVSHA; /** * Initializes SHA-1 or SHA-2 hashing. * * @param context pointer to the function context (of size av_sha_size) * @param bits number of bits in digest (SHA-1 - 160 bits, SHA-2 224 or 256 bits) * @return zero if initialization succeeded, -1 otherwise */ int av_sha_init(struct AVSHA* context, int bits); /** * Updates hash value. * * @param context hash function context * @param data input data to update hash with * @param len input data length */ void av_sha_update(struct AVSHA* context, const uint8_t* data, unsigned int len); /** * Finishes hashing and output digest value. * * @param context hash function context * @param digest buffer where output digest value is stored */ void av_sha_final(struct AVSHA* context, uint8_t *digest); #endif /* AVUTIL_SHA_H */
123linslouis-android-video-cutter
jni/libavutil/sha.h
C
asf20
1,746
/* * arbitrary precision integers * Copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * arbitrary precision integers * @author Michael Niedermayer <michaelni@gmx.at> */ #ifndef AVUTIL_INTEGER_H #define AVUTIL_INTEGER_H #include <stdint.h> #include "common.h" #define AV_INTEGER_SIZE 8 typedef struct AVInteger{ uint16_t v[AV_INTEGER_SIZE]; } AVInteger; AVInteger av_add_i(AVInteger a, AVInteger b) av_const; AVInteger av_sub_i(AVInteger a, AVInteger b) av_const; /** * Returns the rounded-down value of the base 2 logarithm of the given * AVInteger. This is simply the index of the most significant bit * which is 1, or 0 if all bits are 0. */ int av_log2_i(AVInteger a) av_const; AVInteger av_mul_i(AVInteger a, AVInteger b) av_const; /** * Returns 0 if a==b, 1 if a>b and -1 if a<b. */ int av_cmp_i(AVInteger a, AVInteger b) av_const; /** * bitwise shift * @param s the number of bits by which the value should be shifted right, may be negative for shifting left */ AVInteger av_shr_i(AVInteger a, int s) av_const; /** * Returns a % b. * @param quot a/b will be stored here. */ AVInteger av_mod_i(AVInteger *quot, AVInteger a, AVInteger b); /** * Returns a/b. */ AVInteger av_div_i(AVInteger a, AVInteger b) av_const; /** * Converts the given int64_t to an AVInteger. */ AVInteger av_int2i(int64_t a) av_const; /** * Converts the given AVInteger to an int64_t. * If the AVInteger is too large to fit into an int64_t, * then only the least significant 64 bits will be used. */ int64_t av_i2int(AVInteger a) av_const; #endif /* AVUTIL_INTEGER_H */
123linslouis-android-video-cutter
jni/libavutil/integer.h
C
asf20
2,387
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_ARM_BSWAP_H #define AVUTIL_ARM_BSWAP_H #include <stdint.h> #include "config.h" #include "libavutil/attributes.h" #ifdef __ARMCC_VERSION #if HAVE_ARMV6 #define bswap_16 bswap_16 static av_always_inline av_const unsigned bswap_16(unsigned x) { __asm { rev16 x, x } return x; } #define bswap_32 bswap_32 static av_always_inline av_const uint32_t bswap_32(uint32_t x) { return __rev(x); } #endif /* HAVE_ARMV6 */ #elif HAVE_INLINE_ASM #if HAVE_ARMV6 #define bswap_16 bswap_16 static av_always_inline av_const unsigned bswap_16(unsigned x) { __asm__("rev16 %0, %0" : "+r"(x)); return x; } #endif #define bswap_32 bswap_32 static av_always_inline av_const uint32_t bswap_32(uint32_t x) { #if HAVE_ARMV6 __asm__("rev %0, %0" : "+r"(x)); #else uint32_t t; __asm__ ("eor %1, %0, %0, ror #16 \n\t" "bic %1, %1, #0xFF0000 \n\t" "mov %0, %0, ror #8 \n\t" "eor %0, %0, %1, lsr #8 \n\t" : "+r"(x), "=&r"(t)); #endif /* HAVE_ARMV6 */ return x; } #endif /* __ARMCC_VERSION */ #endif /* AVUTIL_ARM_BSWAP_H */
123linslouis-android-video-cutter
jni/libavutil/arm/bswap.h
C
asf20
1,876
/* * Copyright (c) 2010 Mans Rullgard <mans@mansr.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_ARM_INTMATH_H #define AVUTIL_ARM_INTMATH_H #include "config.h" #include "libavutil/attributes.h" #if HAVE_INLINE_ASM #if HAVE_ARMV6 static inline av_const int FASTDIV(int a, int b) { int r, t; __asm__ volatile("cmp %3, #2 \n\t" "ldr %1, [%4, %3, lsl #2] \n\t" "lsrle %0, %2, #1 \n\t" "smmulgt %0, %1, %2 \n\t" : "=&r"(r), "=&r"(t) : "r"(a), "r"(b), "r"(ff_inverse)); return r; } #else static inline av_const int FASTDIV(int a, int b) { int r, t; __asm__ volatile("umull %1, %0, %2, %3" : "=&r"(r), "=&r"(t) : "r"(a), "r"(ff_inverse[b])); return r; } #endif #define FASTDIV FASTDIV #endif /* HAVE_INLINE_ASM */ #endif /* AVUTIL_ARM_INTMATH_H */
123linslouis-android-video-cutter
jni/libavutil/arm/intmath.h
C
asf20
1,658
/* * Copyright (c) 2009 Mans Rullgard <mans@mansr.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_ARM_TIMER_H #define AVUTIL_ARM_TIMER_H #include <stdint.h> #include "config.h" #if HAVE_INLINE_ASM && defined(__ARM_ARCH_7A__) #define AV_READ_TIME read_time static inline uint64_t read_time(void) { unsigned cc; __asm__ volatile ("mrc p15, 0, %0, c9, c13, 0" : "=r"(cc)); return cc; } #endif /* HAVE_INLINE_ASM && __ARM_ARCH_7A__ */ #endif /* AVUTIL_ARM_TIMER_H */
123linslouis-android-video-cutter
jni/libavutil/arm/timer.h
C
asf20
1,218
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_ARM_INTREADWRITE_H #define AVUTIL_ARM_INTREADWRITE_H #include <stdint.h> #include "config.h" #if HAVE_FAST_UNALIGNED && HAVE_INLINE_ASM #define AV_RN16 AV_RN16 static av_always_inline uint16_t AV_RN16(const void *p) { uint16_t v; __asm__ ("ldrh %0, %1" : "=r"(v) : "m"(*(const uint16_t *)p)); return v; } #define AV_WN16 AV_WN16 static av_always_inline void AV_WN16(void *p, uint16_t v) { __asm__ ("strh %1, %0" : "=m"(*(uint16_t *)p) : "r"(v)); } #define AV_RN32 AV_RN32 static av_always_inline uint32_t AV_RN32(const void *p) { uint32_t v; __asm__ ("ldr %0, %1" : "=r"(v) : "m"(*(const uint32_t *)p)); return v; } #define AV_WN32 AV_WN32 static av_always_inline void AV_WN32(void *p, uint32_t v) { __asm__ ("str %1, %0" : "=m"(*(uint32_t *)p) : "r"(v)); } #define AV_RN64 AV_RN64 static av_always_inline uint64_t AV_RN64(const void *p) { union { uint64_t v; uint32_t hl[2]; } v; __asm__ ("ldr %0, %2 \n\t" "ldr %1, %3 \n\t" : "=&r"(v.hl[0]), "=r"(v.hl[1]) : "m"(*(const uint32_t*)p), "m"(*((const uint32_t*)p+1))); return v.v; } #define AV_WN64 AV_WN64 static av_always_inline void AV_WN64(void *p, uint64_t v) { union { uint64_t v; uint32_t hl[2]; } vv = { v }; __asm__ ("str %2, %0 \n\t" "str %3, %1 \n\t" : "=m"(*(uint32_t*)p), "=m"(*((uint32_t*)p+1)) : "r"(vv.hl[0]), "r"(vv.hl[1])); } #endif /* HAVE_INLINE_ASM */ #endif /* AVUTIL_ARM_INTREADWRITE_H */
123linslouis-android-video-cutter
jni/libavutil/arm/intreadwrite.h
C
asf20
2,291
/* * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_SOFTFLOAT_H #define AVUTIL_SOFTFLOAT_H #include <stdint.h> #include "common.h" #define MIN_EXP -126 #define MAX_EXP 126 #define ONE_BITS 29 typedef struct SoftFloat{ int32_t exp; int32_t mant; }SoftFloat; static av_const SoftFloat av_normalize_sf(SoftFloat a){ if(a.mant){ #if 1 while((a.mant + 0x20000000U)<0x40000000U){ a.mant += a.mant; a.exp -= 1; } #else int s=ONE_BITS + 1 - av_log2(a.mant ^ (a.mant<<1)); a.exp -= s; a.mant <<= s; #endif if(a.exp < MIN_EXP){ a.exp = MIN_EXP; a.mant= 0; } }else{ a.exp= MIN_EXP; } return a; } static inline av_const SoftFloat av_normalize1_sf(SoftFloat a){ #if 1 if(a.mant + 0x40000000 < 0){ a.exp++; a.mant>>=1; } return a; #elif 1 int t= a.mant + 0x40000000 < 0; return (SoftFloat){a.exp+t, a.mant>>t}; #else int t= (a.mant + 0x40000000U)>>31; return (SoftFloat){a.exp+t, a.mant>>t}; #endif } /** * @return Will not be more denormalized than a+b. So if either input is * normalized, then the output will not be worse then the other input. * If both are normalized, then the output will be normalized. */ static inline av_const SoftFloat av_mul_sf(SoftFloat a, SoftFloat b){ a.exp += b.exp; a.mant = (a.mant * (int64_t)b.mant) >> ONE_BITS; return av_normalize1_sf(a); } /** * b has to be normalized and not zero. * @return Will not be more denormalized than a. */ static av_const SoftFloat av_div_sf(SoftFloat a, SoftFloat b){ a.exp -= b.exp+1; a.mant = ((int64_t)a.mant<<(ONE_BITS+1)) / b.mant; return av_normalize1_sf(a); } static inline av_const int av_cmp_sf(SoftFloat a, SoftFloat b){ int t= a.exp - b.exp; if(t<0) return (a.mant >> (-t)) - b.mant ; else return a.mant - (b.mant >> t); } static inline av_const SoftFloat av_add_sf(SoftFloat a, SoftFloat b){ int t= a.exp - b.exp; if(t<0) return av_normalize1_sf((SoftFloat){b.exp, b.mant + (a.mant >> (-t))}); else return av_normalize1_sf((SoftFloat){a.exp, a.mant + (b.mant >> t )}); } static inline av_const SoftFloat av_sub_sf(SoftFloat a, SoftFloat b){ return av_add_sf(a, (SoftFloat){b.exp, -b.mant}); } //FIXME sqrt, log, exp, pow, sin, cos static inline av_const SoftFloat av_int2sf(int v, int frac_bits){ return av_normalize_sf((SoftFloat){ONE_BITS-frac_bits, v}); } /** * Rounding is to -inf. */ static inline av_const int av_sf2int(SoftFloat v, int frac_bits){ v.exp += frac_bits - ONE_BITS; if(v.exp >= 0) return v.mant << v.exp ; else return v.mant >>(-v.exp); } #endif /* AVUTIL_SOFTFLOAT_H */
123linslouis-android-video-cutter
jni/libavutil/softfloat.h
C
asf20
3,573
/* * copyright (c) 2008 Aurelien Jacobs <aurel@gnuage.org> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_CRC_DATA_H #define AVUTIL_CRC_DATA_H #include "crc.h" static const AVCRC av_crc_table[AV_CRC_MAX][257] = { [AV_CRC_8_ATM] = { 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D, 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D, 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD, 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD, 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA, 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A, 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A, 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A, 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4, 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4, 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44, 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34, 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63, 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13, 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83, 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3, 0x01 }, [AV_CRC_16_ANSI] = { 0x0000, 0x0580, 0x0F80, 0x0A00, 0x1B80, 0x1E00, 0x1400, 0x1180, 0x3380, 0x3600, 0x3C00, 0x3980, 0x2800, 0x2D80, 0x2780, 0x2200, 0x6380, 0x6600, 0x6C00, 0x6980, 0x7800, 0x7D80, 0x7780, 0x7200, 0x5000, 0x5580, 0x5F80, 0x5A00, 0x4B80, 0x4E00, 0x4400, 0x4180, 0xC380, 0xC600, 0xCC00, 0xC980, 0xD800, 0xDD80, 0xD780, 0xD200, 0xF000, 0xF580, 0xFF80, 0xFA00, 0xEB80, 0xEE00, 0xE400, 0xE180, 0xA000, 0xA580, 0xAF80, 0xAA00, 0xBB80, 0xBE00, 0xB400, 0xB180, 0x9380, 0x9600, 0x9C00, 0x9980, 0x8800, 0x8D80, 0x8780, 0x8200, 0x8381, 0x8601, 0x8C01, 0x8981, 0x9801, 0x9D81, 0x9781, 0x9201, 0xB001, 0xB581, 0xBF81, 0xBA01, 0xAB81, 0xAE01, 0xA401, 0xA181, 0xE001, 0xE581, 0xEF81, 0xEA01, 0xFB81, 0xFE01, 0xF401, 0xF181, 0xD381, 0xD601, 0xDC01, 0xD981, 0xC801, 0xCD81, 0xC781, 0xC201, 0x4001, 0x4581, 0x4F81, 0x4A01, 0x5B81, 0x5E01, 0x5401, 0x5181, 0x7381, 0x7601, 0x7C01, 0x7981, 0x6801, 0x6D81, 0x6781, 0x6201, 0x2381, 0x2601, 0x2C01, 0x2981, 0x3801, 0x3D81, 0x3781, 0x3201, 0x1001, 0x1581, 0x1F81, 0x1A01, 0x0B81, 0x0E01, 0x0401, 0x0181, 0x0383, 0x0603, 0x0C03, 0x0983, 0x1803, 0x1D83, 0x1783, 0x1203, 0x3003, 0x3583, 0x3F83, 0x3A03, 0x2B83, 0x2E03, 0x2403, 0x2183, 0x6003, 0x6583, 0x6F83, 0x6A03, 0x7B83, 0x7E03, 0x7403, 0x7183, 0x5383, 0x5603, 0x5C03, 0x5983, 0x4803, 0x4D83, 0x4783, 0x4203, 0xC003, 0xC583, 0xCF83, 0xCA03, 0xDB83, 0xDE03, 0xD403, 0xD183, 0xF383, 0xF603, 0xFC03, 0xF983, 0xE803, 0xED83, 0xE783, 0xE203, 0xA383, 0xA603, 0xAC03, 0xA983, 0xB803, 0xBD83, 0xB783, 0xB203, 0x9003, 0x9583, 0x9F83, 0x9A03, 0x8B83, 0x8E03, 0x8403, 0x8183, 0x8002, 0x8582, 0x8F82, 0x8A02, 0x9B82, 0x9E02, 0x9402, 0x9182, 0xB382, 0xB602, 0xBC02, 0xB982, 0xA802, 0xAD82, 0xA782, 0xA202, 0xE382, 0xE602, 0xEC02, 0xE982, 0xF802, 0xFD82, 0xF782, 0xF202, 0xD002, 0xD582, 0xDF82, 0xDA02, 0xCB82, 0xCE02, 0xC402, 0xC182, 0x4382, 0x4602, 0x4C02, 0x4982, 0x5802, 0x5D82, 0x5782, 0x5202, 0x7002, 0x7582, 0x7F82, 0x7A02, 0x6B82, 0x6E02, 0x6402, 0x6182, 0x2002, 0x2582, 0x2F82, 0x2A02, 0x3B82, 0x3E02, 0x3402, 0x3182, 0x1382, 0x1602, 0x1C02, 0x1982, 0x0802, 0x0D82, 0x0782, 0x0202, 0x0001 }, [AV_CRC_16_CCITT] = { 0x0000, 0x2110, 0x4220, 0x6330, 0x8440, 0xA550, 0xC660, 0xE770, 0x0881, 0x2991, 0x4AA1, 0x6BB1, 0x8CC1, 0xADD1, 0xCEE1, 0xEFF1, 0x3112, 0x1002, 0x7332, 0x5222, 0xB552, 0x9442, 0xF772, 0xD662, 0x3993, 0x1883, 0x7BB3, 0x5AA3, 0xBDD3, 0x9CC3, 0xFFF3, 0xDEE3, 0x6224, 0x4334, 0x2004, 0x0114, 0xE664, 0xC774, 0xA444, 0x8554, 0x6AA5, 0x4BB5, 0x2885, 0x0995, 0xEEE5, 0xCFF5, 0xACC5, 0x8DD5, 0x5336, 0x7226, 0x1116, 0x3006, 0xD776, 0xF666, 0x9556, 0xB446, 0x5BB7, 0x7AA7, 0x1997, 0x3887, 0xDFF7, 0xFEE7, 0x9DD7, 0xBCC7, 0xC448, 0xE558, 0x8668, 0xA778, 0x4008, 0x6118, 0x0228, 0x2338, 0xCCC9, 0xEDD9, 0x8EE9, 0xAFF9, 0x4889, 0x6999, 0x0AA9, 0x2BB9, 0xF55A, 0xD44A, 0xB77A, 0x966A, 0x711A, 0x500A, 0x333A, 0x122A, 0xFDDB, 0xDCCB, 0xBFFB, 0x9EEB, 0x799B, 0x588B, 0x3BBB, 0x1AAB, 0xA66C, 0x877C, 0xE44C, 0xC55C, 0x222C, 0x033C, 0x600C, 0x411C, 0xAEED, 0x8FFD, 0xECCD, 0xCDDD, 0x2AAD, 0x0BBD, 0x688D, 0x499D, 0x977E, 0xB66E, 0xD55E, 0xF44E, 0x133E, 0x322E, 0x511E, 0x700E, 0x9FFF, 0xBEEF, 0xDDDF, 0xFCCF, 0x1BBF, 0x3AAF, 0x599F, 0x788F, 0x8891, 0xA981, 0xCAB1, 0xEBA1, 0x0CD1, 0x2DC1, 0x4EF1, 0x6FE1, 0x8010, 0xA100, 0xC230, 0xE320, 0x0450, 0x2540, 0x4670, 0x6760, 0xB983, 0x9893, 0xFBA3, 0xDAB3, 0x3DC3, 0x1CD3, 0x7FE3, 0x5EF3, 0xB102, 0x9012, 0xF322, 0xD232, 0x3542, 0x1452, 0x7762, 0x5672, 0xEAB5, 0xCBA5, 0xA895, 0x8985, 0x6EF5, 0x4FE5, 0x2CD5, 0x0DC5, 0xE234, 0xC324, 0xA014, 0x8104, 0x6674, 0x4764, 0x2454, 0x0544, 0xDBA7, 0xFAB7, 0x9987, 0xB897, 0x5FE7, 0x7EF7, 0x1DC7, 0x3CD7, 0xD326, 0xF236, 0x9106, 0xB016, 0x5766, 0x7676, 0x1546, 0x3456, 0x4CD9, 0x6DC9, 0x0EF9, 0x2FE9, 0xC899, 0xE989, 0x8AB9, 0xABA9, 0x4458, 0x6548, 0x0678, 0x2768, 0xC018, 0xE108, 0x8238, 0xA328, 0x7DCB, 0x5CDB, 0x3FEB, 0x1EFB, 0xF98B, 0xD89B, 0xBBAB, 0x9ABB, 0x754A, 0x545A, 0x376A, 0x167A, 0xF10A, 0xD01A, 0xB32A, 0x923A, 0x2EFD, 0x0FED, 0x6CDD, 0x4DCD, 0xAABD, 0x8BAD, 0xE89D, 0xC98D, 0x267C, 0x076C, 0x645C, 0x454C, 0xA23C, 0x832C, 0xE01C, 0xC10C, 0x1FEF, 0x3EFF, 0x5DCF, 0x7CDF, 0x9BAF, 0xBABF, 0xD98F, 0xF89F, 0x176E, 0x367E, 0x554E, 0x745E, 0x932E, 0xB23E, 0xD10E, 0xF01E, 0x0001 }, [AV_CRC_32_IEEE] = { 0x00000000, 0xB71DC104, 0x6E3B8209, 0xD926430D, 0xDC760413, 0x6B6BC517, 0xB24D861A, 0x0550471E, 0xB8ED0826, 0x0FF0C922, 0xD6D68A2F, 0x61CB4B2B, 0x649B0C35, 0xD386CD31, 0x0AA08E3C, 0xBDBD4F38, 0x70DB114C, 0xC7C6D048, 0x1EE09345, 0xA9FD5241, 0xACAD155F, 0x1BB0D45B, 0xC2969756, 0x758B5652, 0xC836196A, 0x7F2BD86E, 0xA60D9B63, 0x11105A67, 0x14401D79, 0xA35DDC7D, 0x7A7B9F70, 0xCD665E74, 0xE0B62398, 0x57ABE29C, 0x8E8DA191, 0x39906095, 0x3CC0278B, 0x8BDDE68F, 0x52FBA582, 0xE5E66486, 0x585B2BBE, 0xEF46EABA, 0x3660A9B7, 0x817D68B3, 0x842D2FAD, 0x3330EEA9, 0xEA16ADA4, 0x5D0B6CA0, 0x906D32D4, 0x2770F3D0, 0xFE56B0DD, 0x494B71D9, 0x4C1B36C7, 0xFB06F7C3, 0x2220B4CE, 0x953D75CA, 0x28803AF2, 0x9F9DFBF6, 0x46BBB8FB, 0xF1A679FF, 0xF4F63EE1, 0x43EBFFE5, 0x9ACDBCE8, 0x2DD07DEC, 0x77708634, 0xC06D4730, 0x194B043D, 0xAE56C539, 0xAB068227, 0x1C1B4323, 0xC53D002E, 0x7220C12A, 0xCF9D8E12, 0x78804F16, 0xA1A60C1B, 0x16BBCD1F, 0x13EB8A01, 0xA4F64B05, 0x7DD00808, 0xCACDC90C, 0x07AB9778, 0xB0B6567C, 0x69901571, 0xDE8DD475, 0xDBDD936B, 0x6CC0526F, 0xB5E61162, 0x02FBD066, 0xBF469F5E, 0x085B5E5A, 0xD17D1D57, 0x6660DC53, 0x63309B4D, 0xD42D5A49, 0x0D0B1944, 0xBA16D840, 0x97C6A5AC, 0x20DB64A8, 0xF9FD27A5, 0x4EE0E6A1, 0x4BB0A1BF, 0xFCAD60BB, 0x258B23B6, 0x9296E2B2, 0x2F2BAD8A, 0x98366C8E, 0x41102F83, 0xF60DEE87, 0xF35DA999, 0x4440689D, 0x9D662B90, 0x2A7BEA94, 0xE71DB4E0, 0x500075E4, 0x892636E9, 0x3E3BF7ED, 0x3B6BB0F3, 0x8C7671F7, 0x555032FA, 0xE24DF3FE, 0x5FF0BCC6, 0xE8ED7DC2, 0x31CB3ECF, 0x86D6FFCB, 0x8386B8D5, 0x349B79D1, 0xEDBD3ADC, 0x5AA0FBD8, 0xEEE00C69, 0x59FDCD6D, 0x80DB8E60, 0x37C64F64, 0x3296087A, 0x858BC97E, 0x5CAD8A73, 0xEBB04B77, 0x560D044F, 0xE110C54B, 0x38368646, 0x8F2B4742, 0x8A7B005C, 0x3D66C158, 0xE4408255, 0x535D4351, 0x9E3B1D25, 0x2926DC21, 0xF0009F2C, 0x471D5E28, 0x424D1936, 0xF550D832, 0x2C769B3F, 0x9B6B5A3B, 0x26D61503, 0x91CBD407, 0x48ED970A, 0xFFF0560E, 0xFAA01110, 0x4DBDD014, 0x949B9319, 0x2386521D, 0x0E562FF1, 0xB94BEEF5, 0x606DADF8, 0xD7706CFC, 0xD2202BE2, 0x653DEAE6, 0xBC1BA9EB, 0x0B0668EF, 0xB6BB27D7, 0x01A6E6D3, 0xD880A5DE, 0x6F9D64DA, 0x6ACD23C4, 0xDDD0E2C0, 0x04F6A1CD, 0xB3EB60C9, 0x7E8D3EBD, 0xC990FFB9, 0x10B6BCB4, 0xA7AB7DB0, 0xA2FB3AAE, 0x15E6FBAA, 0xCCC0B8A7, 0x7BDD79A3, 0xC660369B, 0x717DF79F, 0xA85BB492, 0x1F467596, 0x1A163288, 0xAD0BF38C, 0x742DB081, 0xC3307185, 0x99908A5D, 0x2E8D4B59, 0xF7AB0854, 0x40B6C950, 0x45E68E4E, 0xF2FB4F4A, 0x2BDD0C47, 0x9CC0CD43, 0x217D827B, 0x9660437F, 0x4F460072, 0xF85BC176, 0xFD0B8668, 0x4A16476C, 0x93300461, 0x242DC565, 0xE94B9B11, 0x5E565A15, 0x87701918, 0x306DD81C, 0x353D9F02, 0x82205E06, 0x5B061D0B, 0xEC1BDC0F, 0x51A69337, 0xE6BB5233, 0x3F9D113E, 0x8880D03A, 0x8DD09724, 0x3ACD5620, 0xE3EB152D, 0x54F6D429, 0x7926A9C5, 0xCE3B68C1, 0x171D2BCC, 0xA000EAC8, 0xA550ADD6, 0x124D6CD2, 0xCB6B2FDF, 0x7C76EEDB, 0xC1CBA1E3, 0x76D660E7, 0xAFF023EA, 0x18EDE2EE, 0x1DBDA5F0, 0xAAA064F4, 0x738627F9, 0xC49BE6FD, 0x09FDB889, 0xBEE0798D, 0x67C63A80, 0xD0DBFB84, 0xD58BBC9A, 0x62967D9E, 0xBBB03E93, 0x0CADFF97, 0xB110B0AF, 0x060D71AB, 0xDF2B32A6, 0x6836F3A2, 0x6D66B4BC, 0xDA7B75B8, 0x035D36B5, 0xB440F7B1, 0x00000001 }, [AV_CRC_32_IEEE_LE] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D, 0x00000001 }, }; #endif /* AVUTIL_CRC_DATA_H */
123linslouis-android-video-cutter
jni/libavutil/crc_data.h
C
asf20
14,354
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * common internal and external API header */ #ifndef AVUTIL_COMMON_H #define AVUTIL_COMMON_H #include <ctype.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "attributes.h" //rounded division & shift #define RSHIFT(a,b) ((a) > 0 ? ((a) + ((1<<(b))>>1))>>(b) : ((a) + ((1<<(b))>>1)-1)>>(b)) /* assume b>0 */ #define ROUNDED_DIV(a,b) (((a)>0 ? (a) + ((b)>>1) : (a) - ((b)>>1))/(b)) #define FFABS(a) ((a) >= 0 ? (a) : (-(a))) #define FFSIGN(a) ((a) > 0 ? 1 : -1) #define FFMAX(a,b) ((a) > (b) ? (a) : (b)) #define FFMAX3(a,b,c) FFMAX(FFMAX(a,b),c) #define FFMIN(a,b) ((a) > (b) ? (b) : (a)) #define FFMIN3(a,b,c) FFMIN(FFMIN(a,b),c) #define FFSWAP(type,a,b) do{type SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0) #define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0])) #define FFALIGN(x, a) (((x)+(a)-1)&~((a)-1)) /* misc math functions */ extern const uint8_t ff_log2_tab[256]; extern const uint8_t av_reverse[256]; static inline av_const int av_log2_c(unsigned int v) { int n = 0; if (v & 0xffff0000) { v >>= 16; n += 16; } if (v & 0xff00) { v >>= 8; n += 8; } n += ff_log2_tab[v]; return n; } static inline av_const int av_log2_16bit_c(unsigned int v) { int n = 0; if (v & 0xff00) { v >>= 8; n += 8; } n += ff_log2_tab[v]; return n; } #ifdef HAVE_AV_CONFIG_H # include "config.h" # include "intmath.h" #endif #ifndef av_log2 # define av_log2 av_log2_c #endif #ifndef av_log2_16bit # define av_log2_16bit av_log2_16bit_c #endif /** * Clips a signed integer value into the amin-amax range. * @param a value to clip * @param amin minimum value of the clip range * @param amax maximum value of the clip range * @return clipped value */ static inline av_const int av_clip(int a, int amin, int amax) { if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** * Clips a signed integer value into the 0-255 range. * @param a value to clip * @return clipped value */ static inline av_const uint8_t av_clip_uint8(int a) { if (a&(~0xFF)) return (-a)>>31; else return a; } /** * Clips a signed integer value into the 0-65535 range. * @param a value to clip * @return clipped value */ static inline av_const uint16_t av_clip_uint16(int a) { if (a&(~0xFFFF)) return (-a)>>31; else return a; } /** * Clips a signed integer value into the -32768,32767 range. * @param a value to clip * @return clipped value */ static inline av_const int16_t av_clip_int16(int a) { if ((a+0x8000) & ~0xFFFF) return (a>>31) ^ 0x7FFF; else return a; } /** * Clips a signed 64-bit integer value into the -2147483648,2147483647 range. * @param a value to clip * @return clipped value */ static inline av_const int32_t av_clipl_int32(int64_t a) { if ((a+0x80000000u) & ~UINT64_C(0xFFFFFFFF)) return (a>>63) ^ 0x7FFFFFFF; else return a; } /** * Clips a float value into the amin-amax range. * @param a value to clip * @param amin minimum value of the clip range * @param amax maximum value of the clip range * @return clipped value */ static inline av_const float av_clipf(float a, float amin, float amax) { if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** Computes ceil(log2(x)). * @param x value used to compute ceil(log2(x)) * @return computed ceiling of log2(x) */ static inline av_const int av_ceil_log2(int x) { return av_log2((x - 1) << 1); } #define MKTAG(a,b,c,d) (a | (b << 8) | (c << 16) | (d << 24)) #define MKBETAG(a,b,c,d) (d | (c << 8) | (b << 16) | (a << 24)) /*! * \def GET_UTF8(val, GET_BYTE, ERROR) * Converts a UTF-8 character (up to 4 bytes long) to its 32-bit UCS-4 encoded form * \param val is the output and should be of type uint32_t. It holds the converted * UCS-4 character and should be a left value. * \param GET_BYTE gets UTF-8 encoded bytes from any proper source. It can be * a function or a statement whose return value or evaluated value is of type * uint8_t. It will be executed up to 4 times for values in the valid UTF-8 range, * and up to 7 times in the general case. * \param ERROR action that should be taken when an invalid UTF-8 byte is returned * from GET_BYTE. It should be a statement that jumps out of the macro, * like exit(), goto, return, break, or continue. */ #define GET_UTF8(val, GET_BYTE, ERROR)\ val= GET_BYTE;\ {\ int ones= 7 - av_log2(val ^ 255);\ if(ones==1)\ ERROR\ val&= 127>>ones;\ while(--ones > 0){\ int tmp= GET_BYTE - 128;\ if(tmp>>6)\ ERROR\ val= (val<<6) + tmp;\ }\ } /*! * \def GET_UTF16(val, GET_16BIT, ERROR) * Converts a UTF-16 character (2 or 4 bytes) to its 32-bit UCS-4 encoded form * \param val is the output and should be of type uint32_t. It holds the converted * UCS-4 character and should be a left value. * \param GET_16BIT gets two bytes of UTF-16 encoded data converted to native endianness. * It can be a function or a statement whose return value or evaluated value is of type * uint16_t. It will be executed up to 2 times. * \param ERROR action that should be taken when an invalid UTF-16 surrogate is * returned from GET_BYTE. It should be a statement that jumps out of the macro, * like exit(), goto, return, break, or continue. */ #define GET_UTF16(val, GET_16BIT, ERROR)\ val = GET_16BIT;\ {\ unsigned int hi = val - 0xD800;\ if (hi < 0x800) {\ val = GET_16BIT - 0xDC00;\ if (val > 0x3FFU || hi > 0x3FFU)\ ERROR\ val += (hi<<10) + 0x10000;\ }\ }\ /*! * \def PUT_UTF8(val, tmp, PUT_BYTE) * Converts a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long). * \param val is an input-only argument and should be of type uint32_t. It holds * a UCS-4 encoded Unicode character that is to be converted to UTF-8. If * val is given as a function it is executed only once. * \param tmp is a temporary variable and should be of type uint8_t. It * represents an intermediate value during conversion that is to be * output by PUT_BYTE. * \param PUT_BYTE writes the converted UTF-8 bytes to any proper destination. * It could be a function or a statement, and uses tmp as the input byte. * For example, PUT_BYTE could be "*output++ = tmp;" PUT_BYTE will be * executed up to 4 times for values in the valid UTF-8 range and up to * 7 times in the general case, depending on the length of the converted * Unicode character. */ #define PUT_UTF8(val, tmp, PUT_BYTE)\ {\ int bytes, shift;\ uint32_t in = val;\ if (in < 0x80) {\ tmp = in;\ PUT_BYTE\ } else {\ bytes = (av_log2(in) + 4) / 5;\ shift = (bytes - 1) * 6;\ tmp = (256 - (256 >> bytes)) | (in >> shift);\ PUT_BYTE\ while (shift >= 6) {\ shift -= 6;\ tmp = 0x80 | ((in >> shift) & 0x3f);\ PUT_BYTE\ }\ }\ } /*! * \def PUT_UTF16(val, tmp, PUT_16BIT) * Converts a 32-bit Unicode character to its UTF-16 encoded form (2 or 4 bytes). * \param val is an input-only argument and should be of type uint32_t. It holds * a UCS-4 encoded Unicode character that is to be converted to UTF-16. If * val is given as a function it is executed only once. * \param tmp is a temporary variable and should be of type uint16_t. It * represents an intermediate value during conversion that is to be * output by PUT_16BIT. * \param PUT_16BIT writes the converted UTF-16 data to any proper destination * in desired endianness. It could be a function or a statement, and uses tmp * as the input byte. For example, PUT_BYTE could be "*output++ = tmp;" * PUT_BYTE will be executed 1 or 2 times depending on input character. */ #define PUT_UTF16(val, tmp, PUT_16BIT)\ {\ uint32_t in = val;\ if (in < 0x10000) {\ tmp = in;\ PUT_16BIT\ } else {\ tmp = 0xD800 | ((in - 0x10000) >> 10);\ PUT_16BIT\ tmp = 0xDC00 | ((in - 0x10000) & 0x3FF);\ PUT_16BIT\ }\ }\ #include "mem.h" #ifdef HAVE_AV_CONFIG_H # include "internal.h" #endif /* HAVE_AV_CONFIG_H */ #endif /* AVUTIL_COMMON_H */
123linslouis-android-video-cutter
jni/libavutil/common.h
C
asf20
9,462
/* * pixel format descriptor * Copyright (c) 2009 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pixfmt.h" #include "pixdesc.h" #include "intreadwrite.h" void read_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component) { AVComponentDescriptor comp= desc->comp[c]; int plane= comp.plane; int depth= comp.depth_minus1+1; int mask = (1<<depth)-1; int shift= comp.shift; int step = comp.step_minus1+1; int flags= desc->flags; if (flags & PIX_FMT_BITSTREAM){ int skip = x*step + comp.offset_plus1-1; const uint8_t *p = data[plane] + y*linesize[plane] + (skip>>3); int shift = 8 - depth - (skip&7); while(w--){ int val = (*p >> shift) & mask; if(read_pal_component) val= data[1][4*val + c]; shift -= step; p -= shift>>3; shift &= 7; *dst++= val; } } else { const uint8_t *p = data[plane]+ y*linesize[plane] + x*step + comp.offset_plus1-1; while(w--){ int val; if(flags & PIX_FMT_BE) val= AV_RB16(p); else val= AV_RL16(p); val = (val>>shift) & mask; if(read_pal_component) val= data[1][4*val + c]; p+= step; *dst++= val; } } } void write_line(const uint16_t *src, uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w) { AVComponentDescriptor comp = desc->comp[c]; int plane = comp.plane; int depth = comp.depth_minus1+1; int step = comp.step_minus1+1; int flags = desc->flags; if (flags & PIX_FMT_BITSTREAM) { int skip = x*step + comp.offset_plus1-1; uint8_t *p = data[plane] + y*linesize[plane] + (skip>>3); int shift = 8 - depth - (skip&7); while (w--) { *p |= *src++ << shift; shift -= step; p -= shift>>3; shift &= 7; } } else { int shift = comp.shift; uint8_t *p = data[plane]+ y*linesize[plane] + x*step + comp.offset_plus1-1; while (w--) { if (flags & PIX_FMT_BE) { uint16_t val = AV_RB16(p) | (*src++<<shift); AV_WB16(p, val); } else { uint16_t val = AV_RL16(p) | (*src++<<shift); AV_WL16(p, val); } p+= step; } } } const AVPixFmtDescriptor av_pix_fmt_descriptors[PIX_FMT_NB] = { [PIX_FMT_YUV420P] = { .name = "yuv420p", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 1, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_YUYV422] = { .name = "yuyv422", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 0, .comp = { {0,1,1,0,7}, /* Y */ {0,3,2,0,7}, /* U */ {0,3,4,0,7}, /* V */ }, }, [PIX_FMT_RGB24] = { .name = "rgb24", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,2,1,0,7}, /* R */ {0,2,2,0,7}, /* G */ {0,2,3,0,7}, /* B */ }, }, [PIX_FMT_BGR24] = { .name = "bgr24", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,2,1,0,7}, /* B */ {0,2,2,0,7}, /* G */ {0,2,3,0,7}, /* R */ }, }, [PIX_FMT_YUV422P] = { .name = "yuv422p", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 0, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_YUV444P] = { .name = "yuv444p", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_YUV410P] = { .name = "yuv410p", .nb_components= 3, .log2_chroma_w= 2, .log2_chroma_h= 2, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_YUV411P] = { .name = "yuv411p", .nb_components= 3, .log2_chroma_w= 2, .log2_chroma_h= 0, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_GRAY8] = { .name = "gray", .nb_components= 1, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,0,7}, /* Y */ }, .flags = PIX_FMT_PAL, }, [PIX_FMT_MONOWHITE] = { .name = "monow", .nb_components= 1, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,0,0}, /* Y */ }, .flags = PIX_FMT_BITSTREAM, }, [PIX_FMT_MONOBLACK] = { .name = "monob", .nb_components= 1, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,7,0}, /* Y */ }, .flags = PIX_FMT_BITSTREAM, }, [PIX_FMT_PAL8] = { .name = "pal8", .nb_components= 1, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,0,7}, }, .flags = PIX_FMT_PAL, }, [PIX_FMT_YUVJ420P] = { .name = "yuvj420p", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 1, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_YUVJ422P] = { .name = "yuvj422p", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 0, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_YUVJ444P] = { .name = "yuvj444p", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_XVMC_MPEG2_MC] = { .name = "xvmcmc", .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_XVMC_MPEG2_IDCT] = { .name = "xvmcidct", .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_UYVY422] = { .name = "uyvy422", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 0, .comp = { {0,1,2,0,7}, /* Y */ {0,3,1,0,7}, /* U */ {0,3,3,0,7}, /* V */ }, }, [PIX_FMT_UYYVYY411] = { .name = "uyyvyy411", .nb_components= 3, .log2_chroma_w= 2, .log2_chroma_h= 0, .comp = { {0,3,2,0,7}, /* Y */ {0,5,1,0,7}, /* U */ {0,5,4,0,7}, /* V */ }, }, [PIX_FMT_BGR8] = { .name = "bgr8", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,6,1}, /* B */ {0,0,1,3,2}, /* G */ {0,0,1,0,2}, /* R */ }, .flags = PIX_FMT_PAL, }, [PIX_FMT_BGR4] = { .name = "bgr4", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,3,1,0,0}, /* B */ {0,3,2,0,1}, /* G */ {0,3,4,0,0}, /* R */ }, .flags = PIX_FMT_BITSTREAM, }, [PIX_FMT_BGR4_BYTE] = { .name = "bgr4_byte", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,3,0}, /* B */ {0,0,1,1,1}, /* G */ {0,0,1,0,0}, /* R */ }, .flags = PIX_FMT_PAL, }, [PIX_FMT_RGB8] = { .name = "rgb8", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,6,1}, /* R */ {0,0,1,3,2}, /* G */ {0,0,1,0,2}, /* B */ }, .flags = PIX_FMT_PAL, }, [PIX_FMT_RGB4] = { .name = "rgb4", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,3,1,0,0}, /* R */ {0,3,2,0,1}, /* G */ {0,3,4,0,0}, /* B */ }, .flags = PIX_FMT_BITSTREAM, }, [PIX_FMT_RGB4_BYTE] = { .name = "rgb4_byte", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,0,1,3,0}, /* R */ {0,0,1,1,1}, /* G */ {0,0,1,0,0}, /* B */ }, .flags = PIX_FMT_PAL, }, [PIX_FMT_NV12] = { .name = "nv12", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 1, .comp = { {0,0,1,0,7}, /* Y */ {1,1,1,0,7}, /* U */ {1,1,2,0,7}, /* V */ }, }, [PIX_FMT_NV21] = { .name = "nv21", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 1, .comp = { {0,0,1,0,7}, /* Y */ {1,1,1,0,7}, /* V */ {1,1,2,0,7}, /* U */ }, }, [PIX_FMT_ARGB] = { .name = "argb", .nb_components= 4, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,3,1,0,7}, /* A */ {0,3,2,0,7}, /* R */ {0,3,3,0,7}, /* G */ {0,3,4,0,7}, /* B */ }, }, [PIX_FMT_RGBA] = { .name = "rgba", .nb_components= 4, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,3,1,0,7}, /* R */ {0,3,2,0,7}, /* G */ {0,3,3,0,7}, /* B */ {0,3,4,0,7}, /* A */ }, }, [PIX_FMT_ABGR] = { .name = "abgr", .nb_components= 4, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,3,1,0,7}, /* A */ {0,3,2,0,7}, /* B */ {0,3,3,0,7}, /* G */ {0,3,4,0,7}, /* R */ }, }, [PIX_FMT_BGRA] = { .name = "bgra", .nb_components= 4, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,3,1,0,7}, /* B */ {0,3,2,0,7}, /* G */ {0,3,3,0,7}, /* R */ {0,3,4,0,7}, /* A */ }, }, [PIX_FMT_GRAY16BE] = { .name = "gray16be", .nb_components= 1, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,1,0,15}, /* Y */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_GRAY16LE] = { .name = "gray16le", .nb_components= 1, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,1,0,15}, /* Y */ }, }, [PIX_FMT_YUV440P] = { .name = "yuv440p", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 1, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_YUVJ440P] = { .name = "yuvj440p", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 1, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ }, }, [PIX_FMT_YUVA420P] = { .name = "yuva420p", .nb_components= 4, .log2_chroma_w= 1, .log2_chroma_h= 1, .comp = { {0,0,1,0,7}, /* Y */ {1,0,1,0,7}, /* U */ {2,0,1,0,7}, /* V */ {3,0,1,0,7}, /* A */ }, }, [PIX_FMT_VDPAU_H264] = { .name = "vdpau_h264", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_VDPAU_MPEG1] = { .name = "vdpau_mpeg1", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_VDPAU_MPEG2] = { .name = "vdpau_mpeg2", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_VDPAU_WMV3] = { .name = "vdpau_wmv3", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_VDPAU_VC1] = { .name = "vdpau_vc1", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_VDPAU_MPEG4] = { .name = "vdpau_mpeg4", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_RGB48BE] = { .name = "rgb48be", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,5,1,0,15}, /* R */ {0,5,3,0,15}, /* G */ {0,5,5,0,15}, /* B */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_RGB48LE] = { .name = "rgb48le", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,5,1,0,15}, /* R */ {0,5,3,0,15}, /* G */ {0,5,5,0,15}, /* B */ }, }, [PIX_FMT_RGB565BE] = { .name = "rgb565be", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,0,3,4}, /* R */ {0,1,1,5,5}, /* G */ {0,1,1,0,4}, /* B */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_RGB565LE] = { .name = "rgb565le", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,2,3,4}, /* R */ {0,1,1,5,5}, /* G */ {0,1,1,0,4}, /* B */ }, }, [PIX_FMT_RGB555BE] = { .name = "rgb555be", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,0,2,4}, /* R */ {0,1,1,5,4}, /* G */ {0,1,1,0,4}, /* B */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_RGB555LE] = { .name = "rgb555le", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,2,2,4}, /* R */ {0,1,1,5,4}, /* G */ {0,1,1,0,4}, /* B */ }, }, [PIX_FMT_RGB444BE] = { .name = "rgb444be", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,0,0,3}, /* R */ {0,1,1,4,3}, /* G */ {0,1,1,0,3}, /* B */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_RGB444LE] = { .name = "rgb444le", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,2,0,3}, /* R */ {0,1,1,4,3}, /* G */ {0,1,1,0,3}, /* B */ }, }, [PIX_FMT_BGR565BE] = { .name = "bgr565be", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,0,3,4}, /* B */ {0,1,1,5,5}, /* G */ {0,1,1,0,4}, /* R */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_BGR565LE] = { .name = "bgr565le", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,2,3,4}, /* B */ {0,1,1,5,5}, /* G */ {0,1,1,0,4}, /* R */ }, }, [PIX_FMT_BGR555BE] = { .name = "bgr555be", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,0,2,4}, /* B */ {0,1,1,5,4}, /* G */ {0,1,1,0,4}, /* R */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_BGR555LE] = { .name = "bgr555le", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,2,2,4}, /* B */ {0,1,1,5,4}, /* G */ {0,1,1,0,4}, /* R */ }, }, [PIX_FMT_BGR444BE] = { .name = "bgr444be", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,0,0,3}, /* B */ {0,1,1,4,3}, /* G */ {0,1,1,0,3}, /* R */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_BGR444LE] = { .name = "bgr444le", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,2,0,3}, /* B */ {0,1,1,4,3}, /* G */ {0,1,1,0,3}, /* R */ }, }, [PIX_FMT_VAAPI_MOCO] = { .name = "vaapi_moco", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_VAAPI_IDCT] = { .name = "vaapi_idct", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_VAAPI_VLD] = { .name = "vaapi_vld", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_YUV420P16LE] = { .name = "yuv420p16le", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 1, .comp = { {0,1,1,0,15}, /* Y */ {1,1,1,0,15}, /* U */ {2,1,1,0,15}, /* V */ }, }, [PIX_FMT_YUV420P16BE] = { .name = "yuv420p16be", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 1, .comp = { {0,1,1,0,15}, /* Y */ {1,1,1,0,15}, /* U */ {2,1,1,0,15}, /* V */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_YUV422P16LE] = { .name = "yuv422p16le", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 0, .comp = { {0,1,1,0,15}, /* Y */ {1,1,1,0,15}, /* U */ {2,1,1,0,15}, /* V */ }, }, [PIX_FMT_YUV422P16BE] = { .name = "yuv422p16be", .nb_components= 3, .log2_chroma_w= 1, .log2_chroma_h= 0, .comp = { {0,1,1,0,15}, /* Y */ {1,1,1,0,15}, /* U */ {2,1,1,0,15}, /* V */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_YUV444P16LE] = { .name = "yuv444p16le", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,1,0,15}, /* Y */ {1,1,1,0,15}, /* U */ {2,1,1,0,15}, /* V */ }, }, [PIX_FMT_YUV444P16BE] = { .name = "yuv444p16be", .nb_components= 3, .log2_chroma_w= 0, .log2_chroma_h= 0, .comp = { {0,1,1,0,15}, /* Y */ {1,1,1,0,15}, /* U */ {2,1,1,0,15}, /* V */ }, .flags = PIX_FMT_BE, }, [PIX_FMT_DXVA2_VLD] = { .name = "dxva2_vld", .log2_chroma_w = 1, .log2_chroma_h = 1, .flags = PIX_FMT_HWACCEL, }, [PIX_FMT_Y400A] = { .name = "y400a", .nb_components= 2, .comp = { {0,1,1,0,7}, /* Y */ {0,1,2,0,7}, /* A */ }, }, }; static enum PixelFormat get_pix_fmt_internal(const char *name) { enum PixelFormat pix_fmt; for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) if (av_pix_fmt_descriptors[pix_fmt].name && !strcmp(av_pix_fmt_descriptors[pix_fmt].name, name)) return pix_fmt; return PIX_FMT_NONE; } #if HAVE_BIGENDIAN # define X_NE(be, le) be #else # define X_NE(be, le) le #endif enum PixelFormat av_get_pix_fmt(const char *name) { enum PixelFormat pix_fmt; if (!strcmp(name, "rgb32")) name = X_NE("argb", "bgra"); else if (!strcmp(name, "bgr32")) name = X_NE("abgr", "rgba"); pix_fmt = get_pix_fmt_internal(name); if (pix_fmt == PIX_FMT_NONE) { char name2[32]; snprintf(name2, sizeof(name2), "%s%s", name, X_NE("be", "le")); pix_fmt = get_pix_fmt_internal(name2); } return pix_fmt; } int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc) { int c, bits = 0; int log2_pixels = pixdesc->log2_chroma_w + pixdesc->log2_chroma_h; for (c = 0; c < pixdesc->nb_components; c++) { int s = c==1 || c==2 ? 0 : log2_pixels; bits += (pixdesc->comp[c].depth_minus1+1) << s; } return bits >> log2_pixels; }
123linslouis-android-video-cutter
jni/libavutil/pixdesc.c
C
asf20
22,645
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * error code definitions */ #ifndef AVUTIL_ERROR_H #define AVUTIL_ERROR_H #include <errno.h> #include "avutil.h" /* error handling */ #if EDOM > 0 #define AVERROR(e) (-(e)) ///< Returns a negative error code from a POSIX error code, to return from library functions. #define AVUNERROR(e) (-(e)) ///< Returns a POSIX error code from a library function error return value. #else /* Some platforms have E* and errno already negated. */ #define AVERROR(e) (e) #define AVUNERROR(e) (e) #endif #if LIBAVUTIL_VERSION_MAJOR < 51 #define AVERROR_INVALIDDATA AVERROR(EINVAL) ///< Invalid data found when processing input #define AVERROR_IO AVERROR(EIO) ///< I/O error #define AVERROR_NOENT AVERROR(ENOENT) ///< No such file or directory #define AVERROR_NOFMT AVERROR(EILSEQ) ///< Unknown format #define AVERROR_NOMEM AVERROR(ENOMEM) ///< Not enough memory #define AVERROR_NOTSUPP AVERROR(ENOSYS) ///< Operation not supported #define AVERROR_NUMEXPECTED AVERROR(EDOM) ///< Number syntax expected in filename #define AVERROR_UNKNOWN AVERROR(EINVAL) ///< Unknown error #endif #define AVERROR_EOF AVERROR(EPIPE) ///< End of file #define AVERROR_PATCHWELCOME (-MKTAG('P','A','W','E')) ///< Not yet implemented in FFmpeg, patches welcome #if LIBAVUTIL_VERSION_MAJOR > 50 #define AVERROR_INVALIDDATA (-MKTAG('I','N','D','A')) ///< Invalid data found when processing input #define AVERROR_NUMEXPECTED (-MKTAG('N','U','E','X')) ///< Number syntax expected in filename #endif /** * Puts a description of the AVERROR code errnum in errbuf. * In case of failure the global variable errno is set to indicate the * error. Even in case of failure av_strerror() will print a generic * error message indicating the errnum provided to errbuf. * * @param errbuf_size the size in bytes of errbuf * @return 0 on success, a negative value if a description for errnum * cannot be found */ int av_strerror(int errnum, char *errbuf, size_t errbuf_size); #endif /* AVUTIL_ERROR_H */
123linslouis-android-video-cutter
jni/libavutil/error.h
C
asf20
2,815
/* * copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_INTFLOAT_READWRITE_H #define AVUTIL_INTFLOAT_READWRITE_H #include <stdint.h> #include "attributes.h" /* IEEE 80 bits extended float */ typedef struct AVExtFloat { uint8_t exponent[2]; uint8_t mantissa[8]; } AVExtFloat; double av_int2dbl(int64_t v) av_const; float av_int2flt(int32_t v) av_const; double av_ext2dbl(const AVExtFloat ext) av_const; int64_t av_dbl2int(double d) av_const; int32_t av_flt2int(float d) av_const; AVExtFloat av_dbl2ext(double d) av_const; #endif /* AVUTIL_INTFLOAT_READWRITE_H */
123linslouis-android-video-cutter
jni/libavutil/intfloat_readwrite.h
C
asf20
1,362
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "log.h" #include "tree.h" typedef struct AVTreeNode{ struct AVTreeNode *child[2]; void *elem; int state; }AVTreeNode; const int av_tree_node_size = sizeof(AVTreeNode); void *av_tree_find(const AVTreeNode *t, void *key, int (*cmp)(void *key, const void *b), void *next[2]){ if(t){ unsigned int v= cmp(key, t->elem); if(v){ if(next) next[v>>31]= t->elem; return av_tree_find(t->child[(v>>31)^1], key, cmp, next); }else{ if(next){ av_tree_find(t->child[0], key, cmp, next); av_tree_find(t->child[1], key, cmp, next); } return t->elem; } } return NULL; } void *av_tree_insert(AVTreeNode **tp, void *key, int (*cmp)(void *key, const void *b), AVTreeNode **next){ AVTreeNode *t= *tp; if(t){ unsigned int v= cmp(t->elem, key); void *ret; if(!v){ if(*next) return t->elem; else if(t->child[0]||t->child[1]){ int i= !t->child[0]; void *next_elem[2]; av_tree_find(t->child[i], key, cmp, next_elem); key= t->elem= next_elem[i]; v= -i; }else{ *next= t; *tp=NULL; return NULL; } } ret= av_tree_insert(&t->child[v>>31], key, cmp, next); if(!ret){ int i= (v>>31) ^ !!*next; AVTreeNode **child= &t->child[i]; t->state += 2*i - 1; if(!(t->state&1)){ if(t->state){ /* The following code is equivalent to if((*child)->state*2 == -t->state) rotate(child, i^1); rotate(tp, i); with rotate(): static void rotate(AVTreeNode **tp, int i){ AVTreeNode *t= *tp; *tp= t->child[i]; t->child[i]= t->child[i]->child[i^1]; (*tp)->child[i^1]= t; i= 4*t->state + 2*(*tp)->state + 12; t ->state= ((0x614586 >> i) & 3)-1; (*tp)->state= ((*tp)->state>>1) + ((0x400EEA >> i) & 3)-1; } but such a rotate function is both bigger and slower */ if((*child)->state*2 == -t->state){ *tp= (*child)->child[i^1]; (*child)->child[i^1]= (*tp)->child[i]; (*tp)->child[i]= *child; *child= (*tp)->child[i^1]; (*tp)->child[i^1]= t; (*tp)->child[0]->state= -((*tp)->state>0); (*tp)->child[1]->state= (*tp)->state<0 ; (*tp)->state=0; }else{ *tp= *child; *child= (*child)->child[i^1]; (*tp)->child[i^1]= t; if((*tp)->state) t->state = 0; else t->state>>= 1; (*tp)->state= -t->state; } } } if(!(*tp)->state ^ !!*next) return key; } return ret; }else{ *tp= *next; *next= NULL; if(*tp){ (*tp)->elem= key; return NULL; }else return key; } } void av_tree_destroy(AVTreeNode *t){ if(t){ av_tree_destroy(t->child[0]); av_tree_destroy(t->child[1]); av_free(t); } } void av_tree_enumerate(AVTreeNode *t, void *opaque, int (*cmp)(void *opaque, void *elem), int (*enu)(void *opaque, void *elem)){ if(t){ int v= cmp ? cmp(opaque, t->elem) : 0; if(v>=0) av_tree_enumerate(t->child[0], opaque, cmp, enu); if(v==0) enu(opaque, t->elem); if(v<=0) av_tree_enumerate(t->child[1], opaque, cmp, enu); } } #ifdef TEST #include "lfg.h" static int check(AVTreeNode *t){ if(t){ int left= check(t->child[0]); int right= check(t->child[1]); if(left>999 || right>999) return 1000; if(right - left != t->state) return 1000; if(t->state>1 || t->state<-1) return 1000; return FFMAX(left, right)+1; } return 0; } static void print(AVTreeNode *t, int depth){ int i; for(i=0; i<depth*4; i++) av_log(NULL, AV_LOG_ERROR, " "); if(t){ av_log(NULL, AV_LOG_ERROR, "Node %p %2d %p\n", t, t->state, t->elem); print(t->child[0], depth+1); print(t->child[1], depth+1); }else av_log(NULL, AV_LOG_ERROR, "NULL\n"); } static int cmp(void *a, const void *b){ return (uint8_t*)a-(const uint8_t*)b; } int main(void){ int i; void *k; AVTreeNode *root= NULL, *node=NULL; AVLFG prng; av_lfg_init(&prng, 1); for(i=0; i<10000; i++){ int j = av_lfg_get(&prng) % 86294; if(check(root) > 999){ av_log(NULL, AV_LOG_ERROR, "FATAL error %d\n", i); print(root, 0); return -1; } av_log(NULL, AV_LOG_ERROR, "inserting %4d\n", j); if(!node) node= av_mallocz(av_tree_node_size); av_tree_insert(&root, (void*)(j+1), cmp, &node); j = av_lfg_get(&prng) % 86294; { AVTreeNode *node2=NULL; av_log(NULL, AV_LOG_ERROR, "removing %4d\n", j); av_tree_insert(&root, (void*)(j+1), cmp, &node2); k= av_tree_find(root, (void*)(j+1), cmp, NULL); if(k) av_log(NULL, AV_LOG_ERROR, "removal failure %d\n", i); } } return 0; } #endif
123linslouis-android-video-cutter
jni/libavutil/tree.c
C
asf20
6,683
/* * Copyright (c) 2007 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AVSTRING_H #define AVUTIL_AVSTRING_H #include <stddef.h> /** * Return non-zero if pfx is a prefix of str. If it is, *ptr is set to * the address of the first character in str after the prefix. * * @param str input string * @param pfx prefix to test * @param ptr updated if the prefix is matched inside str * @return non-zero if the prefix matches, zero otherwise */ int av_strstart(const char *str, const char *pfx, const char **ptr); /** * Return non-zero if pfx is a prefix of str independent of case. If * it is, *ptr is set to the address of the first character in str * after the prefix. * * @param str input string * @param pfx prefix to test * @param ptr updated if the prefix is matched inside str * @return non-zero if the prefix matches, zero otherwise */ int av_stristart(const char *str, const char *pfx, const char **ptr); /** * Locate the first case-independent occurrence in the string haystack * of the string needle. A zero-length string needle is considered to * match at the start of haystack. * * This function is a case-insensitive version of the standard strstr(). * * @param haystack string to search in * @param needle string to search for * @return pointer to the located match within haystack * or a null pointer if no match */ char *av_stristr(const char *haystack, const char *needle); /** * Copy the string src to dst, but no more than size - 1 bytes, and * null-terminate dst. * * This function is the same as BSD strlcpy(). * * @param dst destination buffer * @param src source string * @param size size of destination buffer * @return the length of src * * WARNING: since the return value is the length of src, src absolutely * _must_ be a properly 0-terminated string, otherwise this will read beyond * the end of the buffer and possibly crash. */ size_t av_strlcpy(char *dst, const char *src, size_t size); /** * Append the string src to the string dst, but to a total length of * no more than size - 1 bytes, and null-terminate dst. * * This function is similar to BSD strlcat(), but differs when * size <= strlen(dst). * * @param dst destination buffer * @param src source string * @param size size of destination buffer * @return the total length of src and dst * * WARNING: since the return value use the length of src and dst, these absolutely * _must_ be a properly 0-terminated strings, otherwise this will read beyond * the end of the buffer and possibly crash. */ size_t av_strlcat(char *dst, const char *src, size_t size); /** * Append output to a string, according to a format. Never write out of * the destination buffer, and always put a terminating 0 within * the buffer. * @param dst destination buffer (string to which the output is * appended) * @param size total size of the destination buffer * @param fmt printf-compatible format string, specifying how the * following parameters are used * @return the length of the string that would have been generated * if enough space had been available */ size_t av_strlcatf(char *dst, size_t size, const char *fmt, ...); /** * Convert a number to a av_malloced string. */ char *av_d2str(double d); #endif /* AVUTIL_AVSTRING_H */
123linslouis-android-video-cutter
jni/libavutil/avstring.h
C
asf20
4,050
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_X86_CPU_H #define AVUTIL_X86_CPU_H #include <stdint.h> #include "config.h" #if ARCH_X86_64 # define REG_a "rax" # define REG_b "rbx" # define REG_c "rcx" # define REG_d "rdx" # define REG_D "rdi" # define REG_S "rsi" # define PTR_SIZE "8" typedef int64_t x86_reg; # define REG_SP "rsp" # define REG_BP "rbp" # define REGBP rbp # define REGa rax # define REGb rbx # define REGc rcx # define REGd rdx # define REGSP rsp #elif ARCH_X86_32 # define REG_a "eax" # define REG_b "ebx" # define REG_c "ecx" # define REG_d "edx" # define REG_D "edi" # define REG_S "esi" # define PTR_SIZE "4" typedef int32_t x86_reg; # define REG_SP "esp" # define REG_BP "ebp" # define REGBP ebp # define REGa eax # define REGb ebx # define REGc ecx # define REGd edx # define REGSP esp #else typedef int x86_reg; #endif #define HAVE_7REGS (ARCH_X86_64 || (HAVE_EBX_AVAILABLE && HAVE_EBP_AVAILABLE)) #define HAVE_6REGS (ARCH_X86_64 || (HAVE_EBX_AVAILABLE || HAVE_EBP_AVAILABLE)) #if ARCH_X86_64 && defined(PIC) # define BROKEN_RELOCATIONS 1 #endif #endif /* AVUTIL_X86_CPU_H */
123linslouis-android-video-cutter
jni/libavutil/x86_cpu.h
C
asf20
2,031
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include <stdio.h> #include <assert.h> #include "softfloat.h" #include "common.h" #include "log.h" #undef printf int main(void){ SoftFloat one= av_int2sf(1, 0); SoftFloat sf1, sf2; double d1, d2; int i, j; av_log_set_level(AV_LOG_DEBUG); d1= 1; for(i= 0; i<10; i++){ d1= 1/(d1+1); } printf("test1 double=%d\n", (int)(d1 * (1<<24))); sf1= one; for(i= 0; i<10; i++){ sf1= av_div_sf(one, av_normalize_sf(av_add_sf(one, sf1))); } printf("test1 sf =%d\n", av_sf2int(sf1, 24)); for(i= 0; i<100; i++){ START_TIMER d1= i; d2= i/100.0; for(j= 0; j<1000; j++){ d1= (d1+1)*d2; } STOP_TIMER("float add mul") } printf("test2 double=%d\n", (int)(d1 * (1<<24))); for(i= 0; i<100; i++){ START_TIMER sf1= av_int2sf(i, 0); sf2= av_div_sf(av_int2sf(i, 2), av_int2sf(200, 3)); for(j= 0; j<1000; j++){ sf1= av_mul_sf(av_add_sf(sf1, one),sf2); } STOP_TIMER("softfloat add mul") } printf("test2 sf =%d (%d %d)\n", av_sf2int(sf1, 24), sf1.exp, sf1.mant); return 0; }
123linslouis-android-video-cutter
jni/libavutil/softfloat.c
C
asf20
2,022
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Macro definitions for various function/variable attributes */ #ifndef AVUTIL_ATTRIBUTES_H #define AVUTIL_ATTRIBUTES_H #ifdef __GNUC__ # define AV_GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > x || __GNUC__ == x && __GNUC_MINOR__ >= y) #else # define AV_GCC_VERSION_AT_LEAST(x,y) 0 #endif #ifndef av_always_inline #if AV_GCC_VERSION_AT_LEAST(3,1) # define av_always_inline __attribute__((always_inline)) inline #else # define av_always_inline inline #endif #endif #ifndef av_noinline #if AV_GCC_VERSION_AT_LEAST(3,1) # define av_noinline __attribute__((noinline)) #else # define av_noinline #endif #endif #ifndef av_pure #if AV_GCC_VERSION_AT_LEAST(3,1) # define av_pure __attribute__((pure)) #else # define av_pure #endif #endif #ifndef av_const #if AV_GCC_VERSION_AT_LEAST(2,6) # define av_const __attribute__((const)) #else # define av_const #endif #endif #ifndef av_cold #if (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(4,3) # define av_cold __attribute__((cold)) #else # define av_cold #endif #endif #ifndef av_flatten #if (!defined(__ICC) || __ICC > 1110) && AV_GCC_VERSION_AT_LEAST(4,1) # define av_flatten __attribute__((flatten)) #else # define av_flatten #endif #endif #ifndef attribute_deprecated #if AV_GCC_VERSION_AT_LEAST(3,1) # define attribute_deprecated __attribute__((deprecated)) #else # define attribute_deprecated #endif #endif #ifndef av_unused #if defined(__GNUC__) # define av_unused __attribute__((unused)) #else # define av_unused #endif #endif #ifndef av_uninit #if defined(__GNUC__) && !defined(__ICC) # define av_uninit(x) x=x #else # define av_uninit(x) x #endif #endif #ifdef __GNUC__ # define av_builtin_constant_p __builtin_constant_p #else # define av_builtin_constant_p(x) 0 #endif #endif /* AVUTIL_ATTRIBUTES_H */
123linslouis-android-video-cutter
jni/libavutil/attributes.h
C
asf20
2,681
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AVUTIL_H #define AVUTIL_AVUTIL_H /** * @file * external API header */ #define AV_STRINGIFY(s) AV_TOSTRING(s) #define AV_TOSTRING(s) #s #define AV_GLUE(a, b) a ## b #define AV_JOIN(a, b) AV_GLUE(a, b) #define AV_PRAGMA(s) _Pragma(#s) #define AV_VERSION_INT(a, b, c) (a<<16 | b<<8 | c) #define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c #define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c) #define LIBAVUTIL_VERSION_MAJOR 50 #define LIBAVUTIL_VERSION_MINOR 15 #define LIBAVUTIL_VERSION_MICRO 1 #define LIBAVUTIL_VERSION_INT AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \ LIBAVUTIL_VERSION_MINOR, \ LIBAVUTIL_VERSION_MICRO) #define LIBAVUTIL_VERSION AV_VERSION(LIBAVUTIL_VERSION_MAJOR, \ LIBAVUTIL_VERSION_MINOR, \ LIBAVUTIL_VERSION_MICRO) #define LIBAVUTIL_BUILD LIBAVUTIL_VERSION_INT #define LIBAVUTIL_IDENT "Lavu" AV_STRINGIFY(LIBAVUTIL_VERSION) /** * Returns the LIBAVUTIL_VERSION_INT constant. */ unsigned avutil_version(void); /** * Returns the libavutil build-time configuration. */ const char *avutil_configuration(void); /** * Returns the libavutil license. */ const char *avutil_license(void); enum AVMediaType { AVMEDIA_TYPE_UNKNOWN = -1, AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA, AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_ATTACHMENT, AVMEDIA_TYPE_NB }; #include "common.h" #include "error.h" #include "mathematics.h" #include "rational.h" #include "intfloat_readwrite.h" #include "log.h" #include "pixfmt.h" #endif /* AVUTIL_AVUTIL_H */
123linslouis-android-video-cutter
jni/libavutil/avutil.h
C
asf20
2,566
/* * Copyright (c) 2009 Baptiste Coudurier <baptiste.coudurier@gmail.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <unistd.h> #include <fcntl.h> #include "timer.h" #include "random_seed.h" uint32_t ff_random_get_seed(void) { uint32_t seed; int fd; if ((fd = open("/dev/random", O_RDONLY)) == -1) fd = open("/dev/urandom", O_RDONLY); if (fd != -1){ int err = read(fd, &seed, 4); close(fd); if (err == 4) return seed; } #ifdef AV_READ_TIME seed = AV_READ_TIME(); #endif // XXX what to do ? return seed; }
123linslouis-android-video-cutter
jni/libavutil/random_seed.c
C
asf20
1,314
/* * RC4 encryption/decryption/pseudo-random number generator * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_RC4_H #define AVUTIL_RC4_H #include <stdint.h> struct AVRC4 { uint8_t state[256]; int x, y; }; /** * \brief Initializes an AVRC4 context. * * \param key_bits must be a multiple of 8 * \param decrypt 0 for encryption, 1 for decryption, currently has no effect */ int av_rc4_init(struct AVRC4 *d, const uint8_t *key, int key_bits, int decrypt); /** * \brief Encrypts / decrypts using the RC4 algorithm. * * \param count number of bytes * \param dst destination array, can be equal to src * \param src source array, can be equal to dst, may be NULL * \param iv not (yet) used for RC4, should be NULL * \param decrypt 0 for encryption, 1 for decryption, not (yet) used */ void av_rc4_crypt(struct AVRC4 *d, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); #endif /* AVUTIL_RC4_H */
123linslouis-android-video-cutter
jni/libavutil/rc4.h
C
asf20
1,669
/* * pixel format descriptor * Copyright (c) 2009 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PIXDESC_H #define AVUTIL_PIXDESC_H #include <inttypes.h> typedef struct AVComponentDescriptor{ uint16_t plane :2; ///< which of the 4 planes contains the component /** * Number of elements between 2 horizontally consecutive pixels minus 1. * Elements are bits for bitstream formats, bytes otherwise. */ uint16_t step_minus1 :3; /** * Number of elements before the component of the first pixel plus 1. * Elements are bits for bitstream formats, bytes otherwise. */ uint16_t offset_plus1 :3; uint16_t shift :3; ///< number of least significant bits that must be shifted away to get the value uint16_t depth_minus1 :4; ///< number of bits in the component minus 1 }AVComponentDescriptor; /** * Descriptor that unambiguously describes how the bits of a pixel are * stored in the up to 4 data planes of an image. It also stores the * subsampling factors and number of components. * * @note This is separate of the colorspace (RGB, YCbCr, YPbPr, JPEG-style YUV * and all the YUV variants) AVPixFmtDescriptor just stores how values * are stored not what these values represent. */ typedef struct AVPixFmtDescriptor{ const char *name; uint8_t nb_components; ///< The number of components each pixel has, (1-4) /** * Amount to shift the luma width right to find the chroma width. * For YV12 this is 1 for example. * chroma_width = -((-luma_width) >> log2_chroma_w) * The note above is needed to ensure rounding up. * This value only refers to the chroma components. */ uint8_t log2_chroma_w; ///< chroma_width = -((-luma_width )>>log2_chroma_w) /** * Amount to shift the luma height right to find the chroma height. * For YV12 this is 1 for example. * chroma_height= -((-luma_height) >> log2_chroma_h) * The note above is needed to ensure rounding up. * This value only refers to the chroma components. */ uint8_t log2_chroma_h; uint8_t flags; /** * Parameters that describe how pixels are packed. If the format * has chroma components, they must be stored in comp[1] and * comp[2]. */ AVComponentDescriptor comp[4]; }AVPixFmtDescriptor; #define PIX_FMT_BE 1 ///< Pixel format is big-endian. #define PIX_FMT_PAL 2 ///< Pixel format has a palette in data[1], values are indexes in this palette. #define PIX_FMT_BITSTREAM 4 ///< All values of a component are bit-wise packed end to end. #define PIX_FMT_HWACCEL 8 ///< Pixel format is an HW accelerated format. /** * The array of all the pixel format descriptors. */ extern const AVPixFmtDescriptor av_pix_fmt_descriptors[]; /** * Reads a line from an image, and writes the values of the * pixel format component c to dst. * * @param data the array containing the pointers to the planes of the image * @param linesizes the array containing the linesizes of the image * @param desc the pixel format descriptor for the image * @param x the horizontal coordinate of the first pixel to read * @param y the vertical coordinate of the first pixel to read * @param w the width of the line to read, that is the number of * values to write to dst * @param read_pal_component if not zero and the format is a paletted * format writes the values corresponding to the palette * component c in data[1] to dst, rather than the palette indexes in * data[0]. The behavior is undefined if the format is not paletted. */ void read_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component); /** * Writes the values from src to the pixel format component c of an * image line. * * @param src array containing the values to write * @param data the array containing the pointers to the planes of the * image to write into. It is supposed to be zeroed. * @param linesizes the array containing the linesizes of the image * @param desc the pixel format descriptor for the image * @param x the horizontal coordinate of the first pixel to write * @param y the vertical coordinate of the first pixel to write * @param w the width of the line to write, that is the number of * values to write to the image line */ void write_line(const uint16_t *src, uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w); /** * Returns the pixel format corresponding to name. * * If there is no pixel format with name name, then looks for a * pixel format with the name corresponding to the native endian * format of name. * For example in a little-endian system, first looks for "gray16", * then for "gray16le". * * Finally if no pixel format has been found, returns PIX_FMT_NONE. */ enum PixelFormat av_get_pix_fmt(const char *name); /** * Returns the number of bits per pixel used by the pixel format * described by pixdesc. * * The returned number of bits refers to the number of bits actually * used for storing the pixel information, that is padding bits are * not counted. */ int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc); #endif /* AVUTIL_PIXDESC_H */
123linslouis-android-video-cutter
jni/libavutil/pixdesc.h
C
asf20
6,137
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "avutil.h" /** * @file * various utility functions */ unsigned avutil_version(void) { return LIBAVUTIL_VERSION_INT; } const char *avutil_configuration(void) { return FFMPEG_CONFIGURATION; } const char *avutil_license(void) { #define LICENSE_PREFIX "libavutil license: " return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1; }
123linslouis-android-video-cutter
jni/libavutil/utils.c
C
asf20
1,151
/* * LZO 1x decompression * Copyright (c) 2006 Reimar Doeffinger * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avutil.h" #include "common.h" //! Avoid e.g. MPlayers fast_memcpy, it slows things down here. #undef memcpy #include <string.h> #include "lzo.h" //! Define if we may write up to 12 bytes beyond the output buffer. #define OUTBUF_PADDED 1 //! Define if we may read up to 8 bytes beyond the input buffer. #define INBUF_PADDED 1 typedef struct LZOContext { const uint8_t *in, *in_end; uint8_t *out_start, *out, *out_end; int error; } LZOContext; /** * \brief Reads one byte from the input buffer, avoiding an overrun. * \return byte read */ static inline int get_byte(LZOContext *c) { if (c->in < c->in_end) return *c->in++; c->error |= AV_LZO_INPUT_DEPLETED; return 1; } #ifdef INBUF_PADDED #define GETB(c) (*(c).in++) #else #define GETB(c) get_byte(&(c)) #endif /** * \brief Decodes a length value in the coding used by lzo. * \param x previous byte value * \param mask bits used from x * \return decoded length value */ static inline int get_len(LZOContext *c, int x, int mask) { int cnt = x & mask; if (!cnt) { while (!(x = get_byte(c))) cnt += 255; cnt += mask + x; } return cnt; } //#define UNALIGNED_LOADSTORE #define BUILTIN_MEMCPY #ifdef UNALIGNED_LOADSTORE #define COPY2(d, s) *(uint16_t *)(d) = *(uint16_t *)(s); #define COPY4(d, s) *(uint32_t *)(d) = *(uint32_t *)(s); #elif defined(BUILTIN_MEMCPY) #define COPY2(d, s) memcpy(d, s, 2); #define COPY4(d, s) memcpy(d, s, 4); #else #define COPY2(d, s) (d)[0] = (s)[0]; (d)[1] = (s)[1]; #define COPY4(d, s) (d)[0] = (s)[0]; (d)[1] = (s)[1]; (d)[2] = (s)[2]; (d)[3] = (s)[3]; #endif /** * \brief Copies bytes from input to output buffer with checking. * \param cnt number of bytes to copy, must be >= 0 */ static inline void copy(LZOContext *c, int cnt) { register const uint8_t *src = c->in; register uint8_t *dst = c->out; if (cnt > c->in_end - src) { cnt = FFMAX(c->in_end - src, 0); c->error |= AV_LZO_INPUT_DEPLETED; } if (cnt > c->out_end - dst) { cnt = FFMAX(c->out_end - dst, 0); c->error |= AV_LZO_OUTPUT_FULL; } #if defined(INBUF_PADDED) && defined(OUTBUF_PADDED) COPY4(dst, src); src += 4; dst += 4; cnt -= 4; if (cnt > 0) #endif memcpy(dst, src, cnt); c->in = src + cnt; c->out = dst + cnt; } static inline void memcpy_backptr(uint8_t *dst, int back, int cnt); /** * \brief Copies previously decoded bytes to current position. * \param back how many bytes back we start * \param cnt number of bytes to copy, must be >= 0 * * cnt > back is valid, this will copy the bytes we just copied, * thus creating a repeating pattern with a period length of back. */ static inline void copy_backptr(LZOContext *c, int back, int cnt) { register const uint8_t *src = &c->out[-back]; register uint8_t *dst = c->out; if (src < c->out_start || src > dst) { c->error |= AV_LZO_INVALID_BACKPTR; return; } if (cnt > c->out_end - dst) { cnt = FFMAX(c->out_end - dst, 0); c->error |= AV_LZO_OUTPUT_FULL; } memcpy_backptr(dst, back, cnt); c->out = dst + cnt; } static inline void memcpy_backptr(uint8_t *dst, int back, int cnt) { const uint8_t *src = &dst[-back]; if (back == 1) { memset(dst, *src, cnt); } else { #ifdef OUTBUF_PADDED COPY2(dst, src); COPY2(dst + 2, src + 2); src += 4; dst += 4; cnt -= 4; if (cnt > 0) { COPY2(dst, src); COPY2(dst + 2, src + 2); COPY2(dst + 4, src + 4); COPY2(dst + 6, src + 6); src += 8; dst += 8; cnt -= 8; } #endif if (cnt > 0) { int blocklen = back; while (cnt > blocklen) { memcpy(dst, src, blocklen); dst += blocklen; cnt -= blocklen; blocklen <<= 1; } memcpy(dst, src, cnt); } } } void av_memcpy_backptr(uint8_t *dst, int back, int cnt) { memcpy_backptr(dst, back, cnt); } int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen) { int state= 0; int x; LZOContext c; c.in = in; c.in_end = (const uint8_t *)in + *inlen; c.out = c.out_start = out; c.out_end = (uint8_t *)out + * outlen; c.error = 0; x = GETB(c); if (x > 17) { copy(&c, x - 17); x = GETB(c); if (x < 16) c.error |= AV_LZO_ERROR; } if (c.in > c.in_end) c.error |= AV_LZO_INPUT_DEPLETED; while (!c.error) { int cnt, back; if (x > 15) { if (x > 63) { cnt = (x >> 5) - 1; back = (GETB(c) << 3) + ((x >> 2) & 7) + 1; } else if (x > 31) { cnt = get_len(&c, x, 31); x = GETB(c); back = (GETB(c) << 6) + (x >> 2) + 1; } else { cnt = get_len(&c, x, 7); back = (1 << 14) + ((x & 8) << 11); x = GETB(c); back += (GETB(c) << 6) + (x >> 2); if (back == (1 << 14)) { if (cnt != 1) c.error |= AV_LZO_ERROR; break; } } } else if(!state){ cnt = get_len(&c, x, 15); copy(&c, cnt + 3); x = GETB(c); if (x > 15) continue; cnt = 1; back = (1 << 11) + (GETB(c) << 2) + (x >> 2) + 1; } else { cnt = 0; back = (GETB(c) << 2) + (x >> 2) + 1; } copy_backptr(&c, back, cnt + 2); state= cnt = x & 3; copy(&c, cnt); x = GETB(c); } *inlen = c.in_end - c.in; if (c.in > c.in_end) *inlen = 0; *outlen = c.out_end - c.out; return c.error; } #ifdef TEST #include <stdio.h> #include <lzo/lzo1x.h> #include "log.h" #define MAXSZ (10*1024*1024) /* Define one of these to 1 if you wish to benchmark liblzo * instead of our native implementation. */ #define BENCHMARK_LIBLZO_SAFE 0 #define BENCHMARK_LIBLZO_UNSAFE 0 int main(int argc, char *argv[]) { FILE *in = fopen(argv[1], "rb"); uint8_t *orig = av_malloc(MAXSZ + 16); uint8_t *comp = av_malloc(2*MAXSZ + 16); uint8_t *decomp = av_malloc(MAXSZ + 16); size_t s = fread(orig, 1, MAXSZ, in); lzo_uint clen = 0; long tmp[LZO1X_MEM_COMPRESS]; int inlen, outlen; int i; av_log_set_level(AV_LOG_DEBUG); lzo1x_999_compress(orig, s, comp, &clen, tmp); for (i = 0; i < 300; i++) { START_TIMER inlen = clen; outlen = MAXSZ; #if BENCHMARK_LIBLZO_SAFE if (lzo1x_decompress_safe(comp, inlen, decomp, &outlen, NULL)) #elif BENCHMARK_LIBLZO_UNSAFE if (lzo1x_decompress(comp, inlen, decomp, &outlen, NULL)) #else if (av_lzo1x_decode(decomp, &outlen, comp, &inlen)) #endif av_log(NULL, AV_LOG_ERROR, "decompression error\n"); STOP_TIMER("lzod") } if (memcmp(orig, decomp, s)) av_log(NULL, AV_LOG_ERROR, "decompression incorrect\n"); else av_log(NULL, AV_LOG_ERROR, "decompression OK\n"); return 0; } #endif
123linslouis-android-video-cutter
jni/libavutil/lzo.c
C
asf20
8,112
/* * Lagged Fibonacci PRNG * Copyright (c) 2008 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_LFG_H #define AVUTIL_LFG_H typedef struct { unsigned int state[64]; int index; } AVLFG; void av_lfg_init(AVLFG *c, unsigned int seed); /** * Gets the next random unsigned 32-bit number using an ALFG. * * Please also consider a simple LCG like state= state*1664525+1013904223, * it may be good enough and faster for your specific use case. */ static inline unsigned int av_lfg_get(AVLFG *c){ c->state[c->index & 63] = c->state[(c->index-24) & 63] + c->state[(c->index-55) & 63]; return c->state[c->index++ & 63]; } /** * Gets the next random unsigned 32-bit number using a MLFG. * * Please also consider av_lfg_get() above, it is faster. */ static inline unsigned int av_mlfg_get(AVLFG *c){ unsigned int a= c->state[(c->index-55) & 63]; unsigned int b= c->state[(c->index-24) & 63]; return c->state[c->index++ & 63] = 2*a*b+a+b; } /** * Gets the next two numbers generated by a Box-Muller Gaussian * generator using the random numbers issued by lfg. * * @param out[2] array where are placed the two generated numbers */ void av_bmg_get(AVLFG *lfg, double out[2]); #endif /* AVUTIL_LFG_H */
123linslouis-android-video-cutter
jni/libavutil/lfg.h
C
asf20
1,986
/* * LZO 1x decompression * copyright (c) 2006 Reimar Doeffinger * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_LZO_H #define AVUTIL_LZO_H #include <stdint.h> /** \defgroup errflags Error flags returned by av_lzo1x_decode * \{ */ //! end of the input buffer reached before decoding finished #define AV_LZO_INPUT_DEPLETED 1 //! decoded data did not fit into output buffer #define AV_LZO_OUTPUT_FULL 2 //! a reference to previously decoded data was wrong #define AV_LZO_INVALID_BACKPTR 4 //! a non-specific error in the compressed bitstream #define AV_LZO_ERROR 8 /** \} */ #define AV_LZO_INPUT_PADDING 8 #define AV_LZO_OUTPUT_PADDING 12 /** * \brief Decodes LZO 1x compressed data. * \param out output buffer * \param outlen size of output buffer, number of bytes left are returned here * \param in input buffer * \param inlen size of input buffer, number of bytes left are returned here * \return 0 on success, otherwise a combination of the error flags above * * Make sure all buffers are appropriately padded, in must provide * AV_LZO_INPUT_PADDING, out must provide AV_LZO_OUTPUT_PADDING additional bytes. */ int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen); /** * \brief deliberately overlapping memcpy implementation * \param dst destination buffer; must be padded with 12 additional bytes * \param back how many bytes back we start (the initial size of the overlapping window) * \param cnt number of bytes to copy, must be >= 0 * * cnt > back is valid, this will copy the bytes we just copied, * thus creating a repeating pattern with a period length of back. */ void av_memcpy_backptr(uint8_t *dst, int back, int cnt); #endif /* AVUTIL_LZO_H */
123linslouis-android-video-cutter
jni/libavutil/lzo.h
C
asf20
2,435
/* * Copyright (c) 2010 Mans Rullgard <mans@mansr.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_TOMI_INTREADWRITE_H #define AVUTIL_TOMI_INTREADWRITE_H #include <stdint.h> #include "config.h" #define AV_RB16 AV_RB16 static av_always_inline uint16_t AV_RB16(const void *p) { uint16_t v; __asm__ ("loadacc, (%1+) \n\t" "rol8 \n\t" "storeacc, %0 \n\t" "loadacc, (%1+) \n\t" "add, %0 \n\t" : "=r"(v), "+a"(p)); return v; } #define AV_WB16 AV_WB16 static av_always_inline void AV_WB16(void *p, uint16_t v) { __asm__ volatile ("loadacc, %1 \n\t" "lsr8 \n\t" "storeacc, (%0+) \n\t" "loadacc, %1 \n\t" "storeacc, (%0+) \n\t" : "+&a"(p) : "r"(v)); } #define AV_RL16 AV_RL16 static av_always_inline uint16_t AV_RL16(const void *p) { uint16_t v; __asm__ ("loadacc, (%1+) \n\t" "storeacc, %0 \n\t" "loadacc, (%1+) \n\t" "rol8 \n\t" "add, %0 \n\t" : "=r"(v), "+a"(p)); return v; } #define AV_WL16 AV_WL16 static av_always_inline void AV_WL16(void *p, uint16_t v) { __asm__ volatile ("loadacc, %1 \n\t" "storeacc, (%0+) \n\t" "lsr8 \n\t" "storeacc, (%0+) \n\t" : "+&a"(p) : "r"(v)); } #define AV_RB32 AV_RB32 static av_always_inline uint32_t AV_RB32(const void *p) { uint32_t v; __asm__ ("loadacc, (%1+) \n\t" "rol8 \n\t" "rol8 \n\t" "rol8 \n\t" "storeacc, %0 \n\t" "loadacc, (%1+) \n\t" "rol8 \n\t" "rol8 \n\t" "add, %0 \n\t" "loadacc, (%1+) \n\t" "rol8 \n\t" "add, %0 \n\t" "loadacc, (%1+) \n\t" "add, %0 \n\t" : "=r"(v), "+a"(p)); return v; } #define AV_WB32 AV_WB32 static av_always_inline void AV_WB32(void *p, uint32_t v) { __asm__ volatile ("loadacc, #4 \n\t" "add, %0 \n\t" "loadacc, %1 \n\t" "storeacc, (-%0) \n\t" "lsr8 \n\t" "storeacc, (-%0) \n\t" "lsr8 \n\t" "storeacc, (-%0) \n\t" "lsr8 \n\t" "storeacc, (-%0) \n\t" : "+&a"(p) : "r"(v)); } #define AV_RL32 AV_RL32 static av_always_inline uint32_t AV_RL32(const void *p) { uint32_t v; __asm__ ("loadacc, (%1+) \n\t" "storeacc, %0 \n\t" "loadacc, (%1+) \n\t" "rol8 \n\t" "add, %0 \n\t" "loadacc, (%1+) \n\t" "rol8 \n\t" "rol8 \n\t" "add, %0 \n\t" "loadacc, (%1+) \n\t" "rol8 \n\t" "rol8 \n\t" "rol8 \n\t" "add, %0 \n\t" : "=r"(v), "+a"(p)); return v; } #define AV_WL32 AV_WL32 static av_always_inline void AV_WL32(void *p, uint32_t v) { __asm__ volatile ("loadacc, %1 \n\t" "storeacc, (%0+) \n\t" "lsr8 \n\t" "storeacc, (%0+) \n\t" "lsr8 \n\t" "storeacc, (%0+) \n\t" "lsr8 \n\t" "storeacc, (%0+) \n\t" : "+&a"(p) : "r"(v)); } #endif /* AVUTIL_TOMI_INTREADWRITE_H */
123linslouis-android-video-cutter
jni/libavutil/tomi/intreadwrite.h
C
asf20
4,740
/* * Copyright (c) 2000, 2001, 2002 Fabrice Bellard * Copyright (c) 2007 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdarg.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include "avstring.h" #include "mem.h" int av_strstart(const char *str, const char *pfx, const char **ptr) { while (*pfx && *pfx == *str) { pfx++; str++; } if (!*pfx && ptr) *ptr = str; return !*pfx; } int av_stristart(const char *str, const char *pfx, const char **ptr) { while (*pfx && toupper((unsigned)*pfx) == toupper((unsigned)*str)) { pfx++; str++; } if (!*pfx && ptr) *ptr = str; return !*pfx; } char *av_stristr(const char *s1, const char *s2) { if (!*s2) return s1; do { if (av_stristart(s1, s2, NULL)) return s1; } while (*s1++); return NULL; } size_t av_strlcpy(char *dst, const char *src, size_t size) { size_t len = 0; while (++len < size && *src) *dst++ = *src++; if (len <= size) *dst = 0; return len + strlen(src) - 1; } size_t av_strlcat(char *dst, const char *src, size_t size) { size_t len = strlen(dst); if (size <= len + 1) return len + strlen(src); return len + av_strlcpy(dst + len, src, size - len); } size_t av_strlcatf(char *dst, size_t size, const char *fmt, ...) { int len = strlen(dst); va_list vl; va_start(vl, fmt); len += vsnprintf(dst + len, size > len ? size - len : 0, fmt, vl); va_end(vl); return len; } char *av_d2str(double d) { char *str= av_malloc(16); if(str) snprintf(str, 16, "%f", d); return str; }
123linslouis-android-video-cutter
jni/libavutil/avstring.c
C
asf20
2,398
/* * Copyright (C) 2007 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_SHA1_H #define AVUTIL_SHA1_H #include <stdint.h> extern const int av_sha1_size; struct AVSHA1; /** * Initializes SHA-1 hashing. * * @param context pointer to the function context (of size av_sha_size) * @deprecated use av_sha_init() instead */ void av_sha1_init(struct AVSHA1* context); /** * Updates hash value. * * @param context hash function context * @param data input data to update hash with * @param len input data length * @deprecated use av_sha_update() instead */ void av_sha1_update(struct AVSHA1* context, const uint8_t* data, unsigned int len); /** * Finishes hashing and output digest value. * * @param context hash function context * @param digest buffer where output digest value is stored * @deprecated use av_sha_final() instead */ void av_sha1_final(struct AVSHA1* context, uint8_t digest[20]); #endif /* AVUTIL_SHA1_H */
123linslouis-android-video-cutter
jni/libavutil/sha1.h
C
asf20
1,718
/* * Copyright (c) 2006 Ryan Martell. (rdm4@martellventures.com) * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @brief Base64 encode/decode * @author Ryan Martell <rdm4@martellventures.com> (with lots of Michael) */ #include "common.h" #include "base64.h" /* ---------------- private code */ static const uint8_t map2[] = { 0x3e, 0xff, 0xff, 0xff, 0x3f, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33 }; int av_base64_decode(uint8_t *out, const char *in, int out_size) { int i, v; uint8_t *dst = out; v = 0; for (i = 0; in[i] && in[i] != '='; i++) { unsigned int index= in[i]-43; if (index>=FF_ARRAY_ELEMS(map2) || map2[index] == 0xff) return -1; v = (v << 6) + map2[index]; if (i & 3) { if (dst - out < out_size) { *dst++ = v >> (6 - 2 * (i & 3)); } } } return dst - out; } /***************************************************************************** * b64_encode: Stolen from VLC's http.c. * Simplified by Michael. * Fixed edge cases and made it work from data (vs. strings) by Ryan. *****************************************************************************/ char *av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size) { static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; char *ret, *dst; unsigned i_bits = 0; int i_shift = 0; int bytes_remaining = in_size; if (in_size >= UINT_MAX / 4 || out_size < (in_size+2) / 3 * 4 + 1) return NULL; ret = dst = out; while (bytes_remaining) { i_bits = (i_bits << 8) + *in++; bytes_remaining--; i_shift += 8; do { *dst++ = b64[(i_bits << 6 >> i_shift) & 0x3f]; i_shift -= 6; } while (i_shift > 6 || (bytes_remaining == 0 && i_shift > 0)); } while ((dst - ret) & 3) *dst++ = '='; *dst = '\0'; return ret; } #ifdef TEST #undef printf #define MAX_DATA_SIZE 1024 #define MAX_ENCODED_SIZE 2048 static int test_encode_decode(const uint8_t *data, unsigned int data_size, const char *encoded_ref) { char encoded[MAX_ENCODED_SIZE]; uint8_t data2[MAX_DATA_SIZE]; int data2_size, max_data2_size = MAX_DATA_SIZE; if (!av_base64_encode(encoded, MAX_ENCODED_SIZE, data, data_size)) { printf("Failed: cannot encode the input data\n"); return 1; } if (encoded_ref && strcmp(encoded, encoded_ref)) { printf("Failed: encoded string differs from reference\n" "Encoded:\n%s\nReference:\n%s\n", encoded, encoded_ref); return 1; } if ((data2_size = av_base64_decode(data2, encoded, max_data2_size)) < 0) { printf("Failed: cannot decode the encoded string\n" "Encoded:\n%s\n", encoded); return 1; } if (memcmp(data2, data, data_size)) { printf("Failed: encoded/decoded data differs from original data\n"); return 1; } printf("Passed!\n"); return 0; } int main(void) { int i, error_count = 0; struct test { const uint8_t *data; const char *encoded_ref; } tests[] = { { "", ""}, { "1", "MQ=="}, { "22", "MjI="}, { "333", "MzMz"}, { "4444", "NDQ0NA=="}, { "55555", "NTU1NTU="}, { "666666", "NjY2NjY2"}, { "abc:def", "YWJjOmRlZg=="}, }; printf("Encoding/decoding tests\n"); for (i = 0; i < FF_ARRAY_ELEMS(tests); i++) error_count += test_encode_decode(tests[i].data, strlen(tests[i].data), tests[i].encoded_ref); return error_count; } #endif
123linslouis-android-video-cutter
jni/libavutil/base64.c
C
asf20
4,906
/* * Copyright (c) 2009 Mans Rullgard <mans@mansr.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_MIPS_INTREADWRITE_H #define AVUTIL_MIPS_INTREADWRITE_H #include <stdint.h> #include "config.h" #define AV_RN32 AV_RN32 static av_always_inline uint32_t AV_RN32(const void *p) { uint32_t v; __asm__ ("lwl %0, %1 \n\t" "lwr %0, %2 \n\t" : "=&r"(v) : "m"(*(const uint32_t *)((const uint8_t *)p+3*!HAVE_BIGENDIAN)), "m"(*(const uint32_t *)((const uint8_t *)p+3*HAVE_BIGENDIAN))); return v; } #define AV_WN32 AV_WN32 static av_always_inline void AV_WN32(void *p, uint32_t v) { __asm__ ("swl %2, %0 \n\t" "swr %2, %1 \n\t" : "=m"(*(uint32_t *)((uint8_t *)p+3*!HAVE_BIGENDIAN)), "=m"(*(uint32_t *)((uint8_t *)p+3*HAVE_BIGENDIAN)) : "r"(v)); } #if ARCH_MIPS64 #define AV_RN64 AV_RN64 static av_always_inline uint64_t AV_RN64(const void *p) { uint64_t v; __asm__ ("ldl %0, %1 \n\t" "ldr %0, %2 \n\t" : "=&r"(v) : "m"(*(const uint64_t *)((const uint8_t *)p+7*!HAVE_BIGENDIAN)), "m"(*(const uint64_t *)((const uint8_t *)p+7*HAVE_BIGENDIAN))); return v; } #define AV_WN64 AV_WN64 static av_always_inline void AV_WN64(void *p, uint64_t v) { __asm__ ("sdl %2, %0 \n\t" "sdr %2, %1 \n\t" : "=m"(*(uint64_t *)((uint8_t *)p+7*!HAVE_BIGENDIAN)), "=m"(*(uint64_t *)((uint8_t *)p+7*HAVE_BIGENDIAN)) : "r"(v)); } #else #define AV_RN64 AV_RN64 static av_always_inline uint64_t AV_RN64(const void *p) { union { uint64_t v; uint32_t hl[2]; } v; v.hl[0] = AV_RN32(p); v.hl[1] = AV_RN32((const uint8_t *)p + 4); return v.v; } #define AV_WN64 AV_WN64 static av_always_inline void AV_WN64(void *p, uint64_t v) { union { uint64_t v; uint32_t hl[2]; } vv = { v }; AV_WN32(p, vv.hl[0]); AV_WN32((uint8_t *)p + 4, vv.hl[1]); } #endif /* ARCH_MIPS64 */ #endif /* AVUTIL_MIPS_INTREADWRITE_H */
123linslouis-android-video-cutter
jni/libavutil/mips/intreadwrite.h
C
asf20
2,789
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PIXFMT_H #define AVUTIL_PIXFMT_H /** * @file * pixel format definitions * * @warning This file has to be considered an internal but installed * header, so it should not be directly included in your projects. */ #include "libavutil/avconfig.h" /** * Pixel format. Notes: * * PIX_FMT_RGB32 is handled in an endian-specific manner. An RGBA * color is put together as: * (A << 24) | (R << 16) | (G << 8) | B * This is stored as BGRA on little-endian CPU architectures and ARGB on * big-endian CPUs. * * When the pixel format is palettized RGB (PIX_FMT_PAL8), the palettized * image data is stored in AVFrame.data[0]. The palette is transported in * AVFrame.data[1], is 1024 bytes long (256 4-byte entries) and is * formatted the same as in PIX_FMT_RGB32 described above (i.e., it is * also endian-specific). Note also that the individual RGB palette * components stored in AVFrame.data[1] should be in the range 0..255. * This is important as many custom PAL8 video codecs that were designed * to run on the IBM VGA graphics adapter use 6-bit palette components. * * For all the 8bit per pixel formats, an RGB32 palette is in data[1] like * for pal8. This palette is filled in automatically by the function * allocating the picture. * * Note, make sure that all newly added big endian formats have pix_fmt&1==1 * and that all newly added little endian formats have pix_fmt&1==0 * this allows simpler detection of big vs little endian. */ enum PixelFormat { PIX_FMT_NONE= -1, PIX_FMT_YUV420P, ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples) PIX_FMT_YUYV422, ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr PIX_FMT_RGB24, ///< packed RGB 8:8:8, 24bpp, RGBRGB... PIX_FMT_BGR24, ///< packed RGB 8:8:8, 24bpp, BGRBGR... PIX_FMT_YUV422P, ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) PIX_FMT_YUV444P, ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples) PIX_FMT_YUV410P, ///< planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples) PIX_FMT_YUV411P, ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) PIX_FMT_GRAY8, ///< Y , 8bpp PIX_FMT_MONOWHITE, ///< Y , 1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb PIX_FMT_MONOBLACK, ///< Y , 1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb PIX_FMT_PAL8, ///< 8 bit with PIX_FMT_RGB32 palette PIX_FMT_YUVJ420P, ///< planar YUV 4:2:0, 12bpp, full scale (JPEG) PIX_FMT_YUVJ422P, ///< planar YUV 4:2:2, 16bpp, full scale (JPEG) PIX_FMT_YUVJ444P, ///< planar YUV 4:4:4, 24bpp, full scale (JPEG) PIX_FMT_XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing PIX_FMT_XVMC_MPEG2_IDCT, PIX_FMT_UYVY422, ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1 PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3 PIX_FMT_BGR8, ///< packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb) PIX_FMT_BGR4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb) PIX_FMT_RGB8, ///< packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb) PIX_FMT_RGB4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb) PIX_FMT_NV12, ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V) PIX_FMT_NV21, ///< as above, but U and V bytes are swapped PIX_FMT_ARGB, ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB... PIX_FMT_RGBA, ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA... PIX_FMT_ABGR, ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR... PIX_FMT_BGRA, ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA... PIX_FMT_GRAY16BE, ///< Y , 16bpp, big-endian PIX_FMT_GRAY16LE, ///< Y , 16bpp, little-endian PIX_FMT_YUV440P, ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples) PIX_FMT_YUVJ440P, ///< planar YUV 4:4:0 full scale (JPEG) PIX_FMT_YUVA420P, ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples) PIX_FMT_VDPAU_H264,///< H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_VDPAU_MPEG1,///< MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_VDPAU_MPEG2,///< MPEG-2 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_VDPAU_WMV3,///< WMV3 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_VDPAU_VC1, ///< VC-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_RGB48BE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian PIX_FMT_RGB48LE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian PIX_FMT_RGB565BE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian PIX_FMT_RGB565LE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian PIX_FMT_RGB555BE, ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0 PIX_FMT_RGB555LE, ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0 PIX_FMT_BGR565BE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), big-endian PIX_FMT_BGR565LE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), little-endian PIX_FMT_BGR555BE, ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1 PIX_FMT_BGR555LE, ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1 PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers PIX_FMT_VAAPI_VLD, ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_YUV420P16LE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian PIX_FMT_YUV420P16BE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian PIX_FMT_YUV422P16LE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian PIX_FMT_YUV422P16BE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian PIX_FMT_YUV444P16LE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian PIX_FMT_YUV444P16BE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian PIX_FMT_VDPAU_MPEG4, ///< MPEG4 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers PIX_FMT_DXVA2_VLD, ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer PIX_FMT_RGB444BE, ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0 PIX_FMT_RGB444LE, ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0 PIX_FMT_BGR444BE, ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1 PIX_FMT_BGR444LE, ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1 PIX_FMT_Y400A, ///< 8bit gray, 8bit alpha PIX_FMT_NB, ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions }; #if AV_HAVE_BIGENDIAN # define PIX_FMT_NE(be, le) PIX_FMT_##be #else # define PIX_FMT_NE(be, le) PIX_FMT_##le #endif #define PIX_FMT_RGB32 PIX_FMT_NE(ARGB, BGRA) #define PIX_FMT_RGB32_1 PIX_FMT_NE(RGBA, ABGR) #define PIX_FMT_BGR32 PIX_FMT_NE(ABGR, RGBA) #define PIX_FMT_BGR32_1 PIX_FMT_NE(BGRA, ARGB) #define PIX_FMT_GRAY16 PIX_FMT_NE(GRAY16BE, GRAY16LE) #define PIX_FMT_RGB48 PIX_FMT_NE(RGB48BE, RGB48LE) #define PIX_FMT_RGB565 PIX_FMT_NE(RGB565BE, RGB565LE) #define PIX_FMT_RGB555 PIX_FMT_NE(RGB555BE, RGB555LE) #define PIX_FMT_RGB444 PIX_FMT_NE(RGB444BE, RGB444LE) #define PIX_FMT_BGR565 PIX_FMT_NE(BGR565BE, BGR565LE) #define PIX_FMT_BGR555 PIX_FMT_NE(BGR555BE, BGR555LE) #define PIX_FMT_BGR444 PIX_FMT_NE(BGR444BE, BGR444LE) #define PIX_FMT_YUV420P16 PIX_FMT_NE(YUV420P16BE, YUV420P16LE) #define PIX_FMT_YUV422P16 PIX_FMT_NE(YUV422P16BE, YUV422P16LE) #define PIX_FMT_YUV444P16 PIX_FMT_NE(YUV444P16BE, YUV444P16LE) #endif /* AVUTIL_PIXFMT_H */
123linslouis-android-video-cutter
jni/libavutil/pixfmt.h
C
asf20
10,645
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * a very simple circular buffer FIFO implementation */ #ifndef AVUTIL_FIFO_H #define AVUTIL_FIFO_H #include <stdint.h> typedef struct AVFifoBuffer { uint8_t *buffer; uint8_t *rptr, *wptr, *end; uint32_t rndx, wndx; } AVFifoBuffer; /** * Initializes an AVFifoBuffer. * @param size of FIFO * @return AVFifoBuffer or NULL in case of memory allocation failure */ AVFifoBuffer *av_fifo_alloc(unsigned int size); /** * Frees an AVFifoBuffer. * @param *f AVFifoBuffer to free */ void av_fifo_free(AVFifoBuffer *f); /** * Resets the AVFifoBuffer to the state right after av_fifo_alloc, in particular it is emptied. * @param *f AVFifoBuffer to reset */ void av_fifo_reset(AVFifoBuffer *f); /** * Returns the amount of data in bytes in the AVFifoBuffer, that is the * amount of data you can read from it. * @param *f AVFifoBuffer to read from * @return size */ int av_fifo_size(AVFifoBuffer *f); /** * Returns the amount of space in bytes in the AVFifoBuffer, that is the * amount of data you can write into it. * @param *f AVFifoBuffer to write into * @return size */ int av_fifo_space(AVFifoBuffer *f); /** * Feeds data from an AVFifoBuffer to a user-supplied callback. * @param *f AVFifoBuffer to read from * @param buf_size number of bytes to read * @param *func generic read function * @param *dest data destination */ int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void (*func)(void*, void*, int)); /** * Feeds data from a user-supplied callback to an AVFifoBuffer. * @param *f AVFifoBuffer to write to * @param *src data source; non-const since it may be used as a * modifiable context by the function defined in func * @param size number of bytes to write * @param *func generic write function; the first parameter is src, * the second is dest_buf, the third is dest_buf_size. * func must return the number of bytes written to dest_buf, or <= 0 to * indicate no more data available to write. * If func is NULL, src is interpreted as a simple byte array for source data. * @return the number of bytes written to the FIFO */ int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int (*func)(void*, void*, int)); /** * Resizes an AVFifoBuffer. * @param *f AVFifoBuffer to resize * @param size new AVFifoBuffer size in bytes * @return <0 for failure, >=0 otherwise */ int av_fifo_realloc2(AVFifoBuffer *f, unsigned int size); /** * Reads and discards the specified amount of data from an AVFifoBuffer. * @param *f AVFifoBuffer to read from * @param size amount of data to read in bytes */ void av_fifo_drain(AVFifoBuffer *f, int size); static inline uint8_t av_fifo_peek(AVFifoBuffer *f, int offs) { uint8_t *ptr = f->rptr + offs; if (ptr >= f->end) ptr -= f->end - f->buffer; return *ptr; } #endif /* AVUTIL_FIFO_H */
123linslouis-android-video-cutter
jni/libavutil/fifo.h
C
asf20
3,615
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Replacements for frequently missing libm functions */ #ifndef AVUTIL_LIBM_H #define AVUTIL_LIBM_H #include <math.h> #include "config.h" #include "attributes.h" #if !HAVE_EXP2 #undef exp2 #define exp2(x) exp((x) * 0.693147180559945) #endif /* HAVE_EXP2 */ #if !HAVE_EXP2F #undef exp2f #define exp2f(x) ((float)exp2(x)) #endif /* HAVE_EXP2F */ #if !HAVE_LLRINT #undef llrint #define llrint(x) ((long long)rint(x)) #endif /* HAVE_LLRINT */ #if !HAVE_LLRINTF #undef llrintf #define llrintf(x) ((long long)rint(x)) #endif /* HAVE_LLRINT */ #if !HAVE_LOG2 #undef log2 #define log2(x) (log(x) * 1.44269504088896340736) #endif /* HAVE_LOG2 */ #if !HAVE_LOG2F #undef log2f #define log2f(x) ((float)log2(x)) #endif /* HAVE_LOG2F */ #if !HAVE_LRINT static av_always_inline av_const long int lrint(double x) { return rint(x); } #endif /* HAVE_LRINT */ #if !HAVE_LRINTF static av_always_inline av_const long int lrintf(float x) { return (int)(rint(x)); } #endif /* HAVE_LRINTF */ #if !HAVE_ROUND static av_always_inline av_const double round(double x) { return (x > 0) ? floor(x + 0.5) : ceil(x - 0.5); } #endif /* HAVE_ROUND */ #if !HAVE_ROUNDF static av_always_inline av_const float roundf(float x) { return (x > 0) ? floor(x + 0.5) : ceil(x - 0.5); } #endif /* HAVE_ROUNDF */ #if !HAVE_TRUNCF static av_always_inline av_const float truncf(float x) { return (x > 0) ? floor(x) : ceil(x); } #endif /* HAVE_TRUNCF */ #endif /* AVUTIL_LIBM_H */
123linslouis-android-video-cutter
jni/libavutil/libm.h
C
asf20
2,246
/* * principal component analysis (PCA) * Copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * principal component analysis (PCA) */ #ifndef AVUTIL_PCA_H #define AVUTIL_PCA_H struct PCA *ff_pca_init(int n); void ff_pca_free(struct PCA *pca); void ff_pca_add(struct PCA *pca, double *v); int ff_pca(struct PCA *pca, double *eigenvector, double *eigenvalue); #endif /* AVUTIL_PCA_H */
123linslouis-android-video-cutter
jni/libavutil/pca.h
C
asf20
1,174
/* * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "common.h" #include "bswap.h" #include "crc.h" #if CONFIG_HARDCODED_TABLES #include "crc_data.h" #else static struct { uint8_t le; uint8_t bits; uint32_t poly; } av_crc_table_params[AV_CRC_MAX] = { [AV_CRC_8_ATM] = { 0, 8, 0x07 }, [AV_CRC_16_ANSI] = { 0, 16, 0x8005 }, [AV_CRC_16_CCITT] = { 0, 16, 0x1021 }, [AV_CRC_32_IEEE] = { 0, 32, 0x04C11DB7 }, [AV_CRC_32_IEEE_LE] = { 1, 32, 0xEDB88320 }, }; static AVCRC av_crc_table[AV_CRC_MAX][257]; #endif /** * Initializes a CRC table. * @param ctx must be an array of size sizeof(AVCRC)*257 or sizeof(AVCRC)*1024 * @param cts_size size of ctx in bytes * @param le If 1, the lowest bit represents the coefficient for the highest * exponent of the corresponding polynomial (both for poly and * actual CRC). * If 0, you must swap the CRC parameter and the result of av_crc * if you need the standard representation (can be simplified in * most cases to e.g. bswap16): * bswap_32(crc << (32-bits)) * @param bits number of bits for the CRC * @param poly generator polynomial without the x**bits coefficient, in the * representation as specified by le * @return <0 on failure */ int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size){ int i, j; uint32_t c; if (bits < 8 || bits > 32 || poly >= (1LL<<bits)) return -1; if (ctx_size != sizeof(AVCRC)*257 && ctx_size != sizeof(AVCRC)*1024) return -1; for (i = 0; i < 256; i++) { if (le) { for (c = i, j = 0; j < 8; j++) c = (c>>1)^(poly & (-(c&1))); ctx[i] = c; } else { for (c = i << 24, j = 0; j < 8; j++) c = (c<<1) ^ ((poly<<(32-bits)) & (((int32_t)c)>>31) ); ctx[i] = bswap_32(c); } } ctx[256]=1; #if !CONFIG_SMALL if(ctx_size >= sizeof(AVCRC)*1024) for (i = 0; i < 256; i++) for(j=0; j<3; j++) ctx[256*(j+1) + i]= (ctx[256*j + i]>>8) ^ ctx[ ctx[256*j + i]&0xFF ]; #endif return 0; } /** * Gets an initialized standard CRC table. * @param crc_id ID of a standard CRC * @return a pointer to the CRC table or NULL on failure */ const AVCRC *av_crc_get_table(AVCRCId crc_id){ #if !CONFIG_HARDCODED_TABLES if (!av_crc_table[crc_id][FF_ARRAY_ELEMS(av_crc_table[crc_id])-1]) if (av_crc_init(av_crc_table[crc_id], av_crc_table_params[crc_id].le, av_crc_table_params[crc_id].bits, av_crc_table_params[crc_id].poly, sizeof(av_crc_table[crc_id])) < 0) return NULL; #endif return av_crc_table[crc_id]; } /** * Calculates the CRC of a block. * @param crc CRC of previous blocks if any or initial value for CRC * @return CRC updated with the data from the given block * * @see av_crc_init() "le" parameter */ uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length){ const uint8_t *end= buffer+length; #if !CONFIG_SMALL if(!ctx[256]) { while(((intptr_t) buffer & 3) && buffer < end) crc = ctx[((uint8_t)crc) ^ *buffer++] ^ (crc >> 8); while(buffer<end-3){ crc ^= le2me_32(*(const uint32_t*)buffer); buffer+=4; crc = ctx[3*256 + ( crc &0xFF)] ^ctx[2*256 + ((crc>>8 )&0xFF)] ^ctx[1*256 + ((crc>>16)&0xFF)] ^ctx[0*256 + ((crc>>24) )]; } } #endif while(buffer<end) crc = ctx[((uint8_t)crc) ^ *buffer++] ^ (crc >> 8); return crc; } #ifdef TEST #undef printf int main(void){ uint8_t buf[1999]; int i; int p[4][3]={{AV_CRC_32_IEEE_LE, 0xEDB88320, 0x3D5CDD04}, {AV_CRC_32_IEEE , 0x04C11DB7, 0xC0F5BAE0}, {AV_CRC_16_ANSI , 0x8005, 0x1FBB }, {AV_CRC_8_ATM , 0x07, 0xE3 },}; const AVCRC *ctx; for(i=0; i<sizeof(buf); i++) buf[i]= i+i*i; for(i=0; i<4; i++){ ctx = av_crc_get_table(p[i][0]); printf("crc %08X =%X\n", p[i][1], av_crc(ctx, 0, buf, sizeof(buf))); } return 0; } #endif
123linslouis-android-video-cutter
jni/libavutil/crc.c
C
asf20
5,125
/* * RC4 encryption/decryption/pseudo-random number generator * Copyright (c) 2007 Reimar Doeffinger * * loosely based on LibTomCrypt by Tom St Denis * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avutil.h" #include "common.h" #include "rc4.h" typedef struct AVRC4 AVRC4; int av_rc4_init(AVRC4 *r, const uint8_t *key, int key_bits, int decrypt) { int i, j; uint8_t y; uint8_t *state = r->state; int keylen = key_bits >> 3; if (key_bits & 7) return -1; for (i = 0; i < 256; i++) state[i] = i; y = 0; // j is i % keylen for (j = 0, i = 0; i < 256; i++, j++) { if (j == keylen) j = 0; y += state[i] + key[j]; FFSWAP(uint8_t, state[i], state[y]); } r->x = 1; r->y = state[1]; return 0; } void av_rc4_crypt(AVRC4 *r, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt) { uint8_t x = r->x, y = r->y; uint8_t *state = r->state; while (count-- > 0) { uint8_t sum = state[x] + state[y]; FFSWAP(uint8_t, state[x], state[y]); *dst++ = src ? *src++ ^ state[sum] : state[sum]; x++; y += state[x]; } r->x = x; r->y = y; }
123linslouis-android-video-cutter
jni/libavutil/rc4.c
C
asf20
1,912